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?