PHP / JSON Object reflection & recursion

August 20th, 2009

If you’re dealing with any complex AJAX these days, you will inevitably run into the issue of how to reflect your objects into JSON. I found this little serialization code snippet, but quickly ran into a problem when dealing with many-to-one child objects.

function toDataObj($myObj) {
    $ref = new ReflectionClass($myObj);
    $data = array();

    foreach (array_values($ref->getMethods()) as $method) {
        if ((0 === strpos($method->name, "get"))
                && $method->isPublic()) {
            $name = substr($method->name, 3);
            $name[0] = strtolower($name[0]);
            $value = $method->invoke($myObj);

			if("object" === gettype($value)) {
                $value = toDataObj($value);
            }

            $data[$name] = $value;
        }
    }

    return $data;
}
print json_encode(toDataObj($myObj));

As you can see at line 12, it only inspects objects that are returned from getters with the “object” type. This is clearly a problem when you have a getter method that returns an array of objects. So, I added a few lines of code to allow for deep recursion, and voila!

function toDataObj($myObj) {
    $ref = new ReflectionClass($myObj);
    $data = array();

    foreach (array_values($ref->getMethods()) as $method) {
        if ((0 === strpos($method->name, "get"))
                && $method->isPublic()) {
            $name = substr($method->name, 3);
            $name[0] = strtolower($name[0]);
            $value = $method->invoke($myObj);

			if("object" === gettype($value)) {
                $value = toDataObj($value);
            } elseif("array" === gettype($value)) {

				$dataArray= array();
				foreach($value as $obj){
					$dataArray[]= toDataObj($obj);
				}

				$value= $dataArray;
            }
            $data[$name] = $value;
        }
    }

    return $data;
}

Leave a Reply