简体   繁体   中英

PHP - non-recursive var_dump?

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";
   }
}

Why don't you simply run a foreach loop on your object?

From the PHP docs :

The foreach construct simply gives an easy way to iterate over arrays. foreach works only on arrays ( and objects ), and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

I had this problem and didn't need to see inside the objects, just the object classnames, so I wrote a simple function to replace objects with their classnames before dumping the data:

function sanitizeDumpContent($content)
{
    if (is_object($content)) return "OBJECT::".get_class($content);

    if (!is_array($content)) return $content;

    return array_map(function($node) {
        return $this->sanitizeDumpContent($node);
    }, $content);
}

Then, when you want to dump something, just do this:

var_dump(sanitizeDumpContent($recursive_content))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM