update page now

Voting

: one minus one?
(Example: nine)

The Note You're Voting On

tomasz dot darmetko at gmail dot com
8 years ago
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;
    }

}

// Outputs: [{"serialized":null},{"serialized":null},{"serialized":{"serialized":null}}]
echo json_encode(
    new SerializableCollection([
        new NestedSerializable(null),
        new NestedSerializable(null),
        new NestedSerializable(new NestedSerializable(null))
    ])
);

?>

<< Back to user notes page

To Top