Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Web =>  PHP

jsonSerialize() in extended class

  sonic0002      2014-07-26 05:54:00      3,810    0    0

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

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious

  RELATED


  0 COMMENT


No comment for this article.


  WRITE ARTICLE

Never ever touch a programmer

By sonic0002