Nested json serializable objects will be serialized recursively. No need to call ->jsonSerialize() on your own. It is especially useful in collections.
<?php
class NestedSerializable implements \JsonSerializable
{
private $serializable;
public function __construct($serializable)
{
$this->serializable = $serializable;
}
public function jsonSerialize()
{
return [
'serialized' => $this->serializable
];
}
}
class SerializableCollection implements \JsonSerializable {
private $elements;
public function __construct(array $elements)
{
$this->elements = $elements;
}
public function jsonSerialize()
{
return $this->elements;
}
}
echo json_encode(
new SerializableCollection([
new NestedSerializable(null),
new NestedSerializable(null),
new NestedSerializable(new NestedSerializable(null))
])
);
?>