Implementing the Iterator Interface

In the previous example, an SPL class was used as an iterator. However, it’s also useful to write your own iterators. This isn’t difficult—iterators are just PHP classes that implement the Iterator interface.

The Iterator interface is a set of five methods: rewind( ), valid( ), key( ), current( ), and next( ). (The names are similar to the old PHP array iteration functions, but they don’t act identically, so don’t confuse them.) These methods tell PHP how to pull the next item from your list, when there are no additional items, how to reset the list and start over from the beginning, and so forth.

When iterating over an object using foreach( ), the methods are called like this:

$it = new MyIterator; // MyIterator is an class that implements Iterator
for ($it->rewind( ); $it->valid( ); $it->next( )) {
    $key = $it->key( );
    $value = $it->current( );
    // code inside the foreach starts here:
    print "$key: $value\n";

You must implement all five methods. However, depending on how your class operates, some of them can be empty.

Table 6-2 describes what each method does and what values they need to return. You cannot pass any information to these methods; instead, you must store data in object properties.

Table 6-2. Iterator interface methods




rewind( )

Resets iterator list to its start

Void (nothing)

valid( )

Says if there are additional items left in the list

true if additional items; false otherwise

Get Upgrading to PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.