Late answer, but I am very surprised no one mentioned what is, arguably, the "correct" way to deploy this functionality.
Implement the JsonSerializable interface on your object. This interface defines one abstract method, jsonSerialize
. That method should return the array representation of your object.
The jsonSerialize
will be called when you attempt to use json_encode
on the object. You can think of this interface as a sort of "magic method" specific to the native JSON encode function, equivalent to __toString
for strings.
Putting it in action, you have an object that looks like this:
class MyFoo implements JsonSerializable {
public $bar = 'hello';
public $baz = 'world';
public function jsonSerialize () {
return array(
'bar'=>$this->bar,
'baz'=>$this->baz
);
}
}
$myFooInstance= new MyFoo();
echo json_encode($myFooInstance); // {"bar":"hello","baz":"world"}
When I am implementing this in my projects, I usually put a toArray
method in the objects, which generates the array, and I have jsonSerialize
use it:
public function jsonSerialize () { return $this->toArray(); }
...this way I can also make use of the array form, if I so choose. This is also handy if you'll be implementing object serialization with __sleep
Documentation
JsonSerializable
- http://php.net/manual/en/class.jsonserializable.php
json_encode
- http://php.net/manual/en/function.json-encode.php