Iterator Interface

Using the foreach construct, you can iterate not only over arrays, but also over instances of classes that implement the Iterator interface (see Chapter 6 for more information on objects and interfaces). To implement the Iterator interface, you must implement five methods on your class:

current()

Returns the element currently pointed at by the iterator

key()

Returns the key for the element currently pointed at by the iterator

next()

Moves the iterator to the next element in the object and returns it

rewind()

Moves the iterator to the first element in the array

valid()

Returns true if the iterator currently points at a valid element, false otherwise

Example 5-5 reimplements a simple iterator class containing a static array of data.

Example 5-5. Iterator interface

class BasicArray implements Iterator
{
  private $position = 0;
  private $array = ["first", "second", "third"];

  public function __construct()
  {
    $this->position = 0;
  }

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

  public function current()
  {
    return $this->array[$this->position]
  }

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

  public function next()
  {
    $this->position += 1;
  }

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

$basicArray = new BasicArray;

foreach ($basicArray as $value) {
  echo "{$value}\n";
}

foreach ($basicArray as $key => $value) {
  echo "{$key} => {$value}\n";
}

first
second
third

0 => first
1 => second
2 => third

When you implement the Iterator interface on a class, it only ...

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.