- URL: https://www.laruence.com/en/2011/10/10/2204.html
- Please include attribution when republishing.
Yesterday funlake reminded me that I should share some of PHP's new developments.
Congratulations on joining the PDT (PHP Developers' Team). Don't forget to let us CN PHPers know about any new progress.
So, today I'll introduce an improvement to Json in 5.4.
Json is the most common data transmission format (protocol) in Ajax applications. All mainstream programming languages have support for Json. In PHP, there is json_encode/json_decode, which can conveniently construct Json data.
<?php echo json_encode(array(1,2,3,4)); ?> //[1,2,3,4]
It can also encode an object into Json:
<?php
$o = new stdclass;
$o->a = 42;
echo json_encode($o);
?>
//{"a":42}
But this brings a problem. Real-world objects are complex, and Json's default behavior of only operating on properties can't always solve the problem. For example, we may want to do some computation via private members to produce the final Json data, or we may want to substitute a string for an object.
In the past, you could only assemble the Json string yourself. But thanks to Sara, in 5.4 Json added a new JsonSerializable interface. Any class that implements this interface must define a jsonSerialize() method. This method is called when an object of this class is encoded to Json, and at that point you can freely adjust the final encoded result:
<?php
class JsonTest implements JsonSerializable {
private $a, $b;
public function __construct($a, $b) {
$this->a = $a;
$this->b = $b;
}
public function jsonSerialize() {
return $this->a + $this->b;
}
}
echo json_encode(new JsonTest(23, 42));
?>
//65
Here's a slightly more complex example:
<?php
$data = array(
new stdClass();
new JsonTest(1,2),
new JsonTest(3,4),
array(5,6)
);
echo json_encode($data);
?>
//[{},3,7,[5,6]]
Finally, a reminder: PHP 5.4 is still under development. Before the final release, any of these features may be adjusted or changed. If you have any suggestions, feedback is welcome, to help make PHP even better.
Thanks
PS: This feature was first introduced by Johannes in his own blog: http://schlueters.de/blog/archives/135-Jason,-let-me-help-you!.html
Be First to Comment