jsonSerialize() in extended class

Summary

PHP's JsonSerializable interface provides a convenient way for objects to define their custom JSON representation through the `jsonSerialize()` method. While simple for standalone classes, handling serialization in an inheritance hierarchy requires a specific approach. When a child class extends a parent that also implements JsonSerializable, merely overriding the `jsonSerialize()` method in the child will only output the child's properties. To ensure the serialized output includes data from both the parent and child classes, the child's `jsonSerialize()` implementation must explicitly call `parent::jsonSerialize()` and merge its returned data with the child's own properties before returning the combined result. This pattern ensures a comprehensive JSON representation for inherited objects.

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"}
JSON INHERITANCE JSONSERIALIZE EXTENDS

  RELATED

  COMMENTS

0

No comment for this article.