Using json_encode on objects in PHP (regardless of scope) Using json_encode on objects in PHP (regardless of scope) php php

Using json_encode on objects in PHP (regardless of scope)


All the properties of your object are private. aka... not available outside their class's scope.

Solution for PHP >= 5.4

Use the new JsonSerializable Interface to provide your own json representation to be used by json_encode

class Thing implements JsonSerializable {    ...    public function jsonSerialize() {        return [            'something' => $this->something,            'protected_something' => $this->get_protected_something(),            'private_something' => $this->get_private_something()        ];    }    ...}

Solution for PHP < 5.4

If you do want to serialize your private and protected object properties, you have to implement a JSON encoding function inside your Class that utilizes json_encode() on a data structure you create for this purpose.

class Thing {    ...    public function to_json() {        return json_encode(array(            'something' => $this->something,            'protected_something' => $this->get_protected_something(),            'private_something' => $this->get_private_something()                        ));    }    ...}

A more detailed writeup


In PHP >= 5.4.0 there is a new interface for serializing objects to JSON : JsonSerializable

Just implement the interface in your object and define a JsonSerializable method which will be called when you use json_encode.

So the solution for PHP >= 5.4.0 should look something like this:

class JsonObject implements JsonSerializable{    // properties    // function called when encoded with json_encode    public function jsonSerialize()    {        return get_object_vars($this);    }}


In RedBeanPHP 2.0 there is a mass-export function which turns an entire collection of beans into arrays. This works with the JSON encoder..

json_encode( R::exportAll( $beans ) );