JSON is the modern data format used in "AJAX" applications. As the leading language for the Web PHP course has support for handling JSON data: You can pass any data to and the function will create a JSON representation of this data:
[php]
[1,2,3,4][/php]
This also works for objects:
[php]
a = 42;echo json_encode($o);?>{"a":42}[/php]
Wonderful. But the world isn't that easy. For many PHP objects the JSON-representation of the data is a bit more complex.for instance what about private properties or maybe you want to calculate some inner values? - In PHP 5.3 you were on your own. but thanks to Sara there's hope in sight: the new interface JsonSerializable. Classes implementing this interface have to provide a method jsonSerialize() which will be called by json_encode() and has to return a JSON-compatible representation of the data by doing whatever you want. So let's take a look:
[php]
a = $a; $this->b = $b; } public function jsonSerialize() { return $this->a + $this->b; }}echo json_encode(new JsonTest(23, 42));?>65[/php]
Now this example in itself is of course useless, but let's create a bigger structure, which includes a few of these objects:
[php]
[{},3,7,[5,6]]
[/php]
Of course you'd usually have more complex serialization logic, but that's left to you.
Now almost certainly somebody will ask "and what about the other way round?" - The only answer there is: Sorry there we can't do much. JSON doesn't encode and meta-information so our generic parser in can't do anything special. But anyways: The new interface will certainly be useful.