Removing Object Properties Before Var_Dumping Them

I’m working on a project at the moment (a PHP library for CouchDB, if you must know) that is designed to make HTTP calls and therefore holds a Guzzle HTTPClient object as an object property. This is great except when I need to debug something and the output of my call to var_dump() is several screens high …

There’s a Magic Method for That

It’s possible to amend the behaviour of var_dump() by declaring a __debugInfo() method in the class defining the object you’re dumping. This magic method will be called automatically when PHP encounters a call to var_dump() or print_r() with an object of this class as the target.

For my example, I just wanted to remove a property called “client” from the object, so the code looks like this:

    public function __debugInfo()
        // remove the $client property because the output is HUGE
        $result = get_object_vars($this);
        return $result;

The get_object_vars() returns all the properties in an array that we can then alter before returning it, and it’s the return value that is used by var_dump(). The array elements still get dumped as object properties, but without that one large property that I wanted to avoid!

One thought on “Removing Object Properties Before Var_Dumping Them

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.