Why does the SplStack class not serialize with the json_encode function?

1

In PHP there is a problem with object serialization. This is usually solved when the class that attempts to serialize implements the JsonSerializable interface.

class Obj implements JsonSerializable
{
   protected $items = array();

   public funciton __construct($items)
   {
      $this->items = $items;
   }

   public function jsonSerialize()
   {
       return $this->items;
   }
}


json_encode(new Obj(array('1', '2', '3')); // "[1, 2, 3]"

I noticed that some classes, even though they are data structures, do not implement this interface. And as a result I had problems - which I did not have in ArrayObject , even though it also does not implement JsonSerializable .

See:

$ a = new SplStack;

$a[] = 1;

$a[] = 2;

$a[] = 3;

var_dump(json_encode($a)); //Imprime: "[]"

As you can see SplStack did not return anything as serialized by json_encode .

Why does this happen to that particular class? Would it be a bug?

    
asked by anonymous 14.10.2015 / 19:23

1 answer

1

In the case of the query example, the return is empty because the items added are inside a private property ( dllist ) so it is not accessible for json_encode() .

If an external function had access to private members of the class, this would violate the encapsulation.

<?php
$a = new SplStack;
$a[] = 1;
$a[] = 2;
$a[] = 3;

echo '<pre>';
print_r($a);

Output:

plStack Object
(
    [flags:SplDoublyLinkedList:private] => 6
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

) 
    
14.10.2015 / 19:38