PHP: Collapsing Object In Var_dump
Jun 25th, 2013When using var_dump() in an object-oriented world, often the output is too big because of objects and therefore not readable. Here a function to collapse objects, and make debugging easier.
To collapse an object, we replace it by a string with its classname:
"Object(Symfony\Component\HttpFoundation\Request)"
We recursively traverse the data structure, replacing each object by a string.
function collapse_objects($data) {
    if (is_object($data)) {
        return sprintf("Object(%s)", get_class($data));
    }
    if (!is_array($data)) {
        return $data;
    }
    foreach ($data as $key => $value) {
        $data[$key] = collapse_objects($value);
    }
    return $data;
}Then, calling var_dump on the data structure with collapsed objects will produce a more readable output:
var_dump(collapse_objects($myObject));