Software Development

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.

[wp_ad_camp_5]

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.

[wp_ad_camp_4]

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+

[wp_ad_camp_3]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like