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.
var_dump() displays values along with data types as output. print_r() displays only value as output. It does not have any return type. It will return a value that is in string format.
var_dump prints out a detailed dump of a variable, including its type and the type of any sub-items (if it's an array or an object). print_r prints a variable in a more human-readable form: strings are not quoted, type information is omitted, array sizes aren't given, etc.
The var_dump() function is used to dump information about a variable. This function displays structured information such as type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions.
We have already learned that var_dump() function is used to display structured information (type and value) about one or more expressions. The function outputs its result directly to the browser.
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With