Converting an Object to JSON in PHP

When developing API interfaces, there are many times you'll want to convert an object into a JSON for appropriate output.   The json_encode function in PHP handles this task quite well with one important caveat.

Let's create a class called Person with some public properties:

class Person
{
    protected $id;
    protected $name;

    public function __construct(array $data) 
    {
        $this->id = $data['id'];
        $this->name = $data['name'];
    }
}

$person = new Person(array('id' => 1, 'name' => 'Amir'));
echo json_encode($person);

The output would be:

{"id":1,"name":"Amir"}

If we decided to make those properties private however, then the output changes to:

{}

 

The json_encode function will not show non-public properties, unfortunately.

There is a solution however. A Jsonserializable interface was added in PHP 5.4 which allows you to accomplish this.

 

class Person implements JsonSerializable
{
    protected $id;
    protected $name;
    
    public function __construct(array $data) 
    {
        $this->id = $data['id'];
        $this->name = $data['name'];
    }
    
    public function getId() 
    {
        return $this->id;
    }
    
    public function getName() 
    {
        return $this->name;
    }

    public function jsonSerialize()
    {
        return 
        [
            'id'   => $this->getId(),
            'name' => $this->getName()
        ];
    }
}
$person = new Person(array('id' => 1, 'name' => 'Amir'));
echo json_encode($person);

Using the new class code above, we see that the output shows what we want:

{"id":1,"name":"Amir"}