O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required