为什么RecursiveIteratorIterator仅在循环中显示元素? [英] Why RecursiveIteratorIterator shows elements only in a loop?

查看:94
本文介绍了为什么RecursiveIteratorIterator仅在循环中显示元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

仅输出


RecursiveIteratorIterator对象

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.

问题:为什么 print_r var_dump show即使在创建对象后该空白?但该循环显示所有数据。 foreach 在运行时循环吗?这不是通常 foreach 的工作方式。对于几乎所有其他事情, var_dump print_r 的事实也告诉了对象包含的所有内容,为什么不为此一个?

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?

推荐答案

foreach 可以处理两种数据:Native array s和实现任何 Traversable 接口的对象,即 InteratorAggregate Iterator

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

如果实现这些接口, foreach 循环将调用某些应该触发发出必要数据的方法。这意味着除非调用方法,否则数据可能不存在。因此,如果数据不存在,则无法转储它。如果你首先迭代对象然后尝试转储数据,它可能不会被保存。

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.

因此,在创建 RecursiveDirectoryIterator 之后,该对象仅保存了以后应该调查的路径。如果你转储它,你就会遇到从PHP内部实现的对象获取内部保存数据的问题。根本没有可以转储的PHP数据结构。

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.

要简化它,并且底线:你可以转储在PHP核心或扩展中实现的对象,但是你只能检测他们的存在,而不是他们的内容。这会影响调试并且不是很好,但遗憾的是PHP的当前状态。

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.

这篇关于为什么RecursiveIteratorIterator仅在循环中显示元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆