Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does PHP use the JsonSerializable interface?

Tags:

php

I'm confused with how JsonSerializable works. Let me elaborate bit more the question.

Normally we use interfaces like this:

<?php
interface Countable {
    /* Methods */
    public function count();    
}

class MyThings implements Countable 
{
    public function count() {
        return count($this->arrayOfThings);
    }
}


$obj = new MyThings();

//call count method on $obj
$obj->count();

So we have a class and it implements the interface. When we call count() function, it is already written in MyThings class. It is simple to understand.

But when we use JsonSerializable interface like this:

<?php
class Thing implements JsonSerializable {
    public function jsonSerialize() {
        // do something 
    }
}
$obj = new Thing();

//call count method on $obj
json_encode($obj);

jsonSerialize() inside Thing runs with the json_encode() call. It is understandable if we call

$obj->jsonSerialize();

then there is a function called jsonSerialize() inside the class. But, how does this work when we run json_encode()? How this is constructed in php? Can someone explain what type of patterns used here?

like image 382
Malintha Abegunarathne Avatar asked Jul 04 '15 07:07

Malintha Abegunarathne


People also ask

How do you implement JsonSerializable?

Add JsonSerializable implementation to the class, by providing the jsonSerialize() method. Now in your application controller or script, when passing the object User to json_encode() you will get the return json encoded array of the jsonSerialize() method instead of the entire object.

What is JsonSerializable?

An object that converts between JSON and the equivalent Foundation objects.

How to serialize JSON in PHP?

The JsonSerializable::jsonSerialize() function is an inbuilt function in PHP which is used to serialize the JSON object to a value that can be serialized natively by using json_encode() function.

How encode JSON in PHP?

Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.


1 Answers

Objects that implement JsonSerializable then implement a jsonSerialize() method. Then, when json_encode() is serializing its input into JSON, if a value that it is serializing is a JsonSerializable, it calls the jsonSerialize() method, and the result of that method is used as the object's serialized representation.

For example, from the PHP documentation:

<?php
class IntegerValue implements JsonSerializable {
    public function __construct($number) {
        $this->number = (integer) $number;
    }

    public function jsonSerialize() {
        return $this->number;
    }
}

echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);

will output

1

which is the json_encoded value representing the number 1. The PHP documentation gives three more examples like this, returning values from the object, but since jsonSerialize() allows you to specify the actual data to be returned, it is important to realize that it can return anything. For example:

class JsonSerializeExample implements JsonSerializable {
    public function jsonSerialize() {
        return [
            'boolean' => true,
            'random_integer' => rand(),
            'int_from_object' => new IntegerValue(42),
            'another_object' => new stdClass,
        ];
    }
}
$obj = new JsonSerializeExample();
echo json_encode($obj, JSON_PRETTY_PRINT);

Will output

{
    "boolean": true,
    "random_integer": 1140562437,
    "int_from_object": 42,
    "another_object": {}
}

Of note is that random_integer is not a static value stored anywhere; it changes on each execution; and int_from_object demonstrates that json_encode() will recursively evaluate JsonSerializable instances.

like image 197
jbafford Avatar answered Sep 28 '22 06:09

jbafford