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

Asked

Viewed 32 times

1

In PHP there is a problem regarding the serialization of the object. Usually this is solved when the class that attempts to serialize implements the interface JsonSerializable.

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 realized that some classes, even if they are data structures, do not implement this interface. And as a result I had problems - what I didn’t have in ArrayObject, even if it also does not implement JsonSerializable.

Behold:

$a = new Splstack;

$a[] = 1;

$a[] = 2;

$a[] = 3;

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

As you can see SplStack returned nothing as serialized by json_encode.

Why does this happen to this particular class? It would be a bug?

1 answer

1

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

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

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

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

Exit:

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

) 
  • There arises another doubt http://answall.com/questions/92495/comorarrayobject-%C3%A9-serialized-by-json-Encode-j%C3%A1-that-same-n%C3%A3o-implementa-js

Browser other questions tagged

You are not signed in. Login or sign up in order to post.