Why RecursiveIteratorIterator shows elements only

2020-07-28 11:04发布

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
print_r($objects);   

This outputs only

RecursiveIteratorIterator Object ( )

But if you loop through the same object like

foreach($objects as $name => $object){
    echo "$name\n";
}

Then it shows all the files and folders like expected.

Question: Why print_r and var_dump show that blank even after Object is created? but that loop shows all the data. Does a foreach loop through those on runtime? That's not how normally foreach works. Also the fact that var_dump or print_r for almost all other things tell everything which the object contains, then why not for this one?

1条回答
走好不送
2楼-- · 2020-07-28 12:08

foreach can work on two kinds of data: Native arrays and objects implementing any of the Traversable interfaces, namely InteratorAggregate and Iterator.

If implementing these interfaces, the foreach loop will call certain methods that should trigger emitting the necessary data. This means the data might not be there unless the methods are called. So if the data is not there, you cannot dump it. And if you first iterated over the object and then try to dump the data, it might not be conserved.

This all is intentional. A good object usually does not start work until explicitly told to do so. Especially a good constructor is not doing any more work than storing the parameters internally and then be done.

So after you created the RecursiveDirectoryIterator, that object merely saved the path it should investigate later. And if you dump it, you'd have the problem of getting the internally saved data back from a PHP-internally implemented object. There simply is no PHP data structure that can be dumped.

To make it short, and bottom line: You can dump objects implemented inside the PHP core or extensions, but you can only detect their presence, not their content. This affects debugging and isn't nice, but sadly the current state of PHP.

查看更多
登录 后发表回答