Since PHP 5.4.0, there is a convenient interface JsonSerializable which can be used to indicate that a PHP object can be serialized to JSON object. It has only one method which should be implemented by any class which implements this interface. The method is named jsonSerialize().
It's really easy to serialize an object to JSON object. Here is one example:
<?php class ArrayValue implements JsonSerializable { public function __construct(array $array) { $this->array = $array; } public function jsonSerialize() { return $this->array; } } $array = [1, 2, 3]; echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT); ?>
Here the output is :
[ 1, 2, 3 ]
This string can be sent back to the client and parsed in JavaScript.
Now have you wondered what we should do when a class B extends another class A and we want to serialize the object of class B. It's not so straight forward at the first glance.
<?php class A implements JsonSerializable{ private $a="A VALUE"; public function jsonSerialize(){ return [ "a" => $this->a ]; } } class B extends A implements JsonSerializable { private $b="B VALUE"; public function jsonSerialize(){ return [ "b" => $this->b ]; } } $b=new B(); echo json_encode($b);
The output of above program will be :
{"b":"B VALUE"}
If we want to show the value of A as well(this is what we expect usually), we need to rewrite the method of jsonSerialize() in class B. The new class B would be look like:
class B extends A implements JsonSerializable { private $b="B VALUE"; public function jsonSerialize(){ $obj = parent::jsonSerialize(); $obj["b"] = $this->b; return $obj; } }
Now the output will be expected:
{"a":"A VALUE","b":"B VALUE"}