Treat a PHP class that implements Iterator as an array

后端 未结 3 884
长发绾君心
长发绾君心 2020-12-16 22:34

If I have a class that implements the Iterator interface, I can manually control how iteration in a foreach loop. But are there other ways in which

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 23:06

    From PHP

    Introduction 
    Interface for external iterators or objects that can be iterated themselves internally.
    

    As you can see from the interface Table of Contents ¶

    Iterator::current — Return the current element
    Iterator::key — Return the key of the current element
    Iterator::next — Move forward to next element
    Iterator::rewind — Rewind the Iterator to the first element
    Iterator::valid — Checks if current position is valid
    

    The operation is designed for forward iteration. So reverse would naturally not work and is not designed for this.

    For more array-object related interfaces take a look at. ArrayAccess and Countable

    For a solution upon a reverse object iterator take a look at the answer here Iterate in reverse through an array with PHP - SPL solution?

提交回复
热议问题