PHP: Collapsing Object In Var_dump

🦖 This post was published in 2013 and is most likely outdated.

When 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));

Comments