Process a PHP class that implements Iterator as an array

If I have a class that implements the interface Iterator, I can manually control how iteration in the loop foreach. But are there other ways my object can behave like an array?

For example, suppose I have a class Guestbookthat implements Iterator, so that I can repeat foreach (new Guestbook() as $entry). But what if I want, say, to reorder?

foreach (array_reverse(new Guestbook()) as $entry)definitely will not work because it array_reversewill only accept an array.

I suppose I ask if I can use Iteratorfor whole whole foreachloops?

Thanks.

+4
source share
3 answers

The purpose of the Iterator interface is to allow the use of your object in a foreach loop, it is not intended to make your object act as an array. If you want something that acts like an array, use an array.

You can always turn your object into an array using the iterator_to_array function , but you cannot cancel this process.

If you see the need to change the order of elements in your iterable object, then you can create a reverse () method that possibly uses array_reverse () internally. Something like that: -

class Test implements Iterator
{
    private $testing = [0,1,2,3,4,5,6,7,8,9,10];
    private $index = 0;

    public function current()
    {
        return $this->testing[$this->index];
    }

    public function next()
    {
        $this->index ++;
    }

    public function key()
    {
        return $this->index;
    }

    public function valid()
    {
        return isset($this->testing[$this->key()]);
    }

    public function rewind()
    {
        $this->index = 0;
    }

    public function reverse()
    {
        $this->testing = array_reverse($this->testing);
        $this->rewind();
    }
}

$tests = new Test();
var_dump(iterator_to_array($tests));
$tests->reverse();
var_dump(iterator_to_array($tests));

Output: -

array (size=11)
  0 => int 0
  1 => int 1
  2 => int 2
  3 => int 3
  4 => int 4
  5 => int 5
  6 => int 6
  7 => int 7
  8 => int 8
  9 => int 9
  10 => int 10

array (size=11)
  0 => int 10
  1 => int 9
  2 => int 8
  3 => int 7
  4 => int 6
  5 => int 5
  6 => int 4
  7 => int 3
  8 => int 2
  9 => int 1
  10 => int 0

I wrote the code to prove to myself that it would work before publication, and thought that I could also pass it back.

+16
source
+2

PHP

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

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

. , , .

, , . ArrayAccess

PHP - SPL?

+1

All Articles