PHP - 使用迭代器的原因? [英] PHP - Reasons to use Iterators?
问题描述
我今天正在阅读手册并注意到各种迭代器。对我来说,似乎它们都毫无意义;我没有理由使用它们,除非你更喜欢它们的语法,或者不知道如何编写递归函数。是否有任何理由在PHP中使用内置迭代器而不仅仅是编写循环或者使用递归方法?
我只是在寻找事实响应,而不是主观偏好(即:我不在乎你是否认为它更可读或更面向对象,我想知道它们是否更快,提供在自己滚动时无法实现的功能等) 。
我认为主要原因是多功能性。它们不会使事情更具可读性,您可以完成 spl iterators <的大部分内容。 / a>使用简单的 foreach
。
但是迭代器可以作为一种压缩循环或循环源你可以传球您可以拥有比列表/数组更多样化的数据源。真正的优点是你可以将它们包装或堆叠以进行聚合。
命名有些不明显,但我想你可以使用 但最终它确实是一种风格选择。如果你有自定义对象遍历某些东西(例如可以指向真实文件或数据库条目的VFS对象),那将是最有意义的。但即便如此,您也可以 唯一的情况是,选择迭代器是非常必要的如果数据源的大小不受限制。在 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.). 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 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. The naming is somewhat unobvious, but I guess you could use the 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 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 这篇关于PHP - 使用迭代器的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! AppendIterator
例如组合一个静态文件名列表和 DirectoryIterator
。或者将其包装在 LimitIterator
中,而不是将其硬连接到
条件。所有这些都是非常基本的功能,可以在foreach中手动完成。但至少 RegexIterator
和
$ b b iterator_to_array
转换此类列表,并使用正常的 foreach
-over-array。
foreach
中使用的展开数组可以消耗比可以逐元素检索的迭代器更多的内存。foreach
.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.iterator_to_array
convert such a list, and use a normal foreach
-over-array.foreach
can consume more memory than an iterator which can retrieve element by element.