PHP 对象作为伪数组
我有一个实现 ArrayAccess 的对象,迭代器 和 可数。 这会产生近乎完美的数组掩蔽。 我可以使用偏移量($object[foo]
)访问它,我可以将它放入 < code>foreach-循环,以及许多其他东西。
但我不能做的是将其提供给本机数组迭代器函数(next()
、reset()
、current()
、 key()
),即使我已经从 Iterator 实现了所需的方法。 PHP 似乎顽固地尝试迭代其成员变量,并且完全忽略迭代器方法。
是否有一个接口可以将对象连接到剩余的数组遍历函数,或者我是否坚持我所拥有的?
更新: IteratorAggregate 似乎也不是答案。 虽然它在 foreach 循环中使用,但基本数组迭代器函数不会调用这些方法。
I have an object that implements ArrayAccess, Iterator and Countable. That produces a nigh-perfect array masking. I can access it with offsets ($object[foo]
), I can throw it into a foreach
-loop, and many other things.
But what I can't do is give it to the native array iterator functions (next()
, reset()
, current()
, key()
), even though I have implemented the required methods from Iterator. PHP seems to stubbornly try to iterate through its member variables, and entirely disregards the iterator-methods.
Is there an interface that would hook the object to the remaining array-traversing-functions, or am I stuck with what I have?
Update: IteratorAggregate doesn't seem to be the answer either. While it is used in foreach
-loops, the basic array iterator functions don't call the methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PHP 最近的更改阻止使用标准数组函数(重置、下一个等)操作 ArrayIterators 形式。
这应该很快就会恢复:
http://news.php.net/php.internals/42015
Recent changes in PHP prevent ArrayIterators form being manipulated using the standard array functions (reset, next, etc).
This should be restored soon:
http://news.php.net/php.internals/42015
实现此目的的一种方法是在单独的类中定义您自己的迭代器,然后告诉您的主类使用新的迭代器而不是默认的迭代器。
那么您应该拥有所需的控制权。 (并且您可以在多个类中重用您自己的 MyIterator)。
以上没有做过测试,但我相信原理是正确的。
希望这可以帮助!
One way to get this to work is to define your own iterator in a separate class, and then tell your main class to use that new iterator instead of the default one.
Then you should have as much control as you need. (And you can reuse your own MyIterator across a number of classes).
No testing done on the above, but the principle is correct, I believe.
Hope this helps!
是 ArrayIterator 不是您要找的吗? 或者 ArrayObject 怎么样,这似乎是 SPL 的接口为了你想要实现的目标。
Is ArrayIterator not what you're looking for? Or what about ArrayObject, which seems to be SPL's interface for what you're trying to achieve.