Encoding a PHP object into JSON representation should be as simple as using the object as a parameter to the function json_encode
, but it isn’t. According to PHP’s manual (here), the value to be encoded is allowed to be of any type, except a resource.
But to accomplish what I was trying to do (encode a PHP object into JSON), I used a function to convert an object to array (found here), and then encoded the array to JSON representation.
Function object_to_array($var)
(found here):
/**
* Convert an object into an associative array
*
* This function converts an object into an associative array by iterating
* over its public properties. Because this function uses the foreach
* construct, Iterators are respected. It also works on arrays of objects.
*
* @return array
*/
function object_to_array($var) {
$result = array();
$references = array();
// loop over elements/properties
foreach ($var as $key => $value) {
// recursively convert objects
if (is_object($value) || is_array($value)) {
// but prevent cycles
if (!in_array($value, $references)) {
$result[$key] = object_to_array($value);
$references[] = $value;
}
} else {
// simple values are untouched
$result[$key] = $value;
}
}
return $result;
}
So I wrote a class called json_encodable
, that includes the above function, and returns the JSON representation of the array we obtained.
Class json_encodable
:
class json_encodable {
public function get_json() {
return json_encode($this->object_to_array($this));
}
}
And, then, I made every class that I wanted to be “JSON encodable” to extend json_encodable
, and, therefore, to have the get_json()
method.
Then, every instance of Class1
, Class2
or Class3
, would have the get_json()
method.
Oh, just another thing! Remember to let the attributes in Class1
, Class2
and Class3
accessible to json_encodable
, setting their visibility to protected
or public
.