PHP - 使用迭代器的原因?
我今天仔细阅读手册并注意到各种迭代器.在我看来,它们似乎都毫无意义;除非您更喜欢它们的语法,或者不知道如何编写递归函数,否则我看不出使用它们的理由.是否有任何理由在 PHP 中使用内置迭代器而不是编写循环或创建递归方法?
I was perusing the manual today and noticed the various iterators. To me, it seems like they are all somewhat pointless; I don't see a reason to use them unless you prefer their syntax, or don't know how to write a recursive function. Are there any reasons to use built-in iterators in PHP over just writing a loop or making a recursive method?
我只是在寻找事实的回应,而不是主观的偏好(即:我不在乎你认为它更可读"还是更面向对象",我想知道它们是否更快,提供滚动您自己的等时无法实现的功能.
I'm only looking for factual responses, not subjective preferences (ie: I don't care if you think it's more "readable" or "more object-oriented", I want to know if they're faster, offer functionality that can't be achieved when rolling your own, etc.).
推荐答案
我认为主要原因是多功能性.它们不会使事情更具可读性,您可以完成 spl 迭代器 用一个简单的 foreach
来做.
I believe the main reason is versatility. They don't make things more readable and you can accomplish most of what the spl iterators do with a simple foreach
.
但迭代器可以作为一种压缩循环或循环源,您可以传递它.您可以拥有比列表/数组更多样化的数据源.真正的优势是您可以包装或堆叠它们以进行聚合.
But iterators can serve as sort of a compacted loop or loop source that you can pass around. You can have more diverse data sources than just a list/array. And the real advantage is that you can wrap or stack them for aggregation.
命名有点不明显,但我想你可以使用 AppendIterator
来例如,结合文件名的静态列表和 DirectoryIterator
的结果.或者以其他方式将其包装在 LimitIterator
中,而不是将其硬接线到 for
条件.所有这些都是非常基本的功能,可以在 foreach 中手动完成.但至少 RegexIterator
和 FilterIterator
似乎适合降低一些复杂性.
The naming is somewhat unobvious, but I guess you could use the AppendIterator
to for example combine a static list of filenames and the result of a DirectoryIterator
. Or otherwise wrap that in a LimitIterator
instead of hardwiring that into a for
condition. All of these are pretty basic features and can be done manually in a foreach. But at least RegexIterator
and FilterIterator
seem suitable to reduce some complexity.
但归根结底,这确实是一种风格选择.如果您有遍历某些东西的自定义对象(例如,可以指向真实文件或数据库条目的 VFS 对象),那将是最有意义的.但即便如此,您也可以 iterator_to_array
转换这样的列表,并使用普通的 foreach
-over-array.
But in the end it's really a stylistic choice. It would make most sense if you have custom objects which traverse something (for example a VFS object which can either point to real files or database entries). But even then you could just iterator_to_array
convert such a list, and use a normal foreach
-over-array.
唯一需要选择迭代器的情况是数据源的大小不受限制.foreach
中使用的展开数组比可以逐个检索元素的迭代器消耗更多的内存.
The only case were it is really imperative to prefer iterators were if the data source is unlimited in size. Unfolded arrays for use in a foreach
can consume more memory than an iterator which can retrieve element by element.
相关文章