Iterators

The Iterator design pattern is where an iterator is used to traverse a container. In PHP, a class is traversable using the foreach construct if it ultimately inherits the Traversable interface. Unfortunately, this is an abstract base interface, you can't implement it alone (unless you're writing in the PHP core itself). Instead, you must instead implement interfaces called Iterator or IteratorAggregate. By implementing either of these interfaces you make a class iterable and traversable using foreach.

Iterator and IteratorAggregate interfaces are very similar, except the IteratorAggregate interface creates an external iterator. IteratorAggregate as an interface only requires outlines one method, getIterator. This method has to return ...

Get Mastering PHP Design Patterns now with the O’Reilly learning platform.

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