This post is archived and probably outdated.

Jason, let me help you!

2010-06-03 19:01:00

In a few previous blog posts I was already talking about changes in PHP's trunk, like some BC break or some new features, time to continue:

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 json_encode() and the function will create a JSON representation of this data:

echo json_encode(array(1,2,3,4));


This also works for objects:

$o = new stdclass;
$o->a = 42;
echo json_encode($o);


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:

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));


Now this example in itself is of course useless, but let's create a bigger structure, which includes a few of these objects:

$data = array(
    new stdClass();
    new JsonTest(1,2),
    new JsonTest(3,4),
echo json_encode($data);


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 json_decode() can't do anything special. But anyways: The new interface will certainly be useful.

At last a short disclaimer: PHP trunk is a development tree. Features in their may be changed at anytime and might not be released. Feedback is welcome.