Menu

Limiting var_dump output

Sometimes to quickly inspect what's in object, PHP var_dump function can be used. This will show all object properties, including private and protected, also of all nested objects.

Sometimes this is just too much to produce useful output.

Fortunately in recent PHP versions, a new magic method was added: __debugInfo. When implementing this method, it should return array with keys as object names, and it's values as values that should be displayed.

The drawback of implementing this method is that it will no longer show real object contents. So use with caution, keep in mind that it might also confuse other developers if they are not aware, that class has this method implemented.

However on complex data models containing arbitrary nested structures it turned out to be useful.

Having meta container it was very easy to create proper output for this method. To ensure that getters and setters are called, method was in fact implemented in external class:

class ModelDumper
{
public static function varDumpPrepare(MongoDocument $model)
{
$values = [];
foreach (Meta::create($model)->fields() as $name => $meta)
{
$values[$name] = $model->$name;
}
return $values;
}
}

And then used in concrete class:

class MyModel
{
...
public function __debugInfo()
{
return ModelDumper::varDumpPrepare($this);
}
...
}

Time will show if it will more useful than full var_dump.

  • Projects