0

How foreach Interacts with Iterator interface

The key to figuring out how PHP Iterators work is understanding how the PHP foreach construct interacts with any implementation of the Iterator interface. With this approach, SPL Iterators are demistified.

The Iterator interface is a native interface that comes with PHP5.0+. It’s somewhat akin to Java’s Iterator interface. It has the following interface declaration:

To help us trace the foreach-Iterator interactions, we use a class the implements the Iterator interface and a set of codes to instantiate and traverse the Iterator object. It is a simple class where each key methods displays its name to the screen.

Below is the output from this code snippet:

The order of the method calls gives us a very good trace on how foreach interacts with Interators.

NOTE: Using PHP 5.5+