When dealing with certain PHP objects, it's possible to do a var_dump()
and PHP prints values to the screen that go on and on and on until the PHP memory limit is reached I assume. An example of this is dumping a Simple HTML DOM object. I assume that because you are able to traverse children and parents of objects, that doing var_dump()
gives infinite results because it finds the parent of an object and then recursively finds it's children and then finds all those children's parents and finds those children, etc etc etc. It will just go on and on.
My question is, how can you avoid this and keep PHP from dumping recursively dumping out the same things over and over? Using the Simple HTML DOM parser example, if I have a DOM object that has no children and I var_dump()
it, I'd like it to just dump the object and no start traversing up the DOM tree and dumping parents, grandparents, other children, etc.
Install XDebug extension in your development environment. It replaces var_dump with its own that only goes 3 members deep by default.
https://xdebug.org/docs/display
It will display items 4 levels deep as an ellipsis. You can change the depth with an ini setting.
All PHP functions: var_dump, var_export, and print_r do not track recursion / circular references.
Edit:
If you want to do it the hard way, you can write your own function
print_rr($thing, $level=0) {
if ($level == 4) { return; }
if (is_object($thing)) {
$vars = get_object_vars($thing);
}
if (is_array($thing)) {
$vars = $thing;
}
if (!$vars) {
print " $thing \n";
return;
}
foreach ($vars as $k=>$v) {
if (is_object($v)) return print_rr($v, $level++);
if (is_array($v)) return print_rr($v, $level++);
print "something like var_dump, var_export output\n";
}
}