Removing Object Properties Before Var_Dumping Them
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); unset($result['client']); 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!
Very useful. Thanks for your article!