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:
1 2 3 4 5 6 7 | interface Iterator extends Traversable { abstract public current(); abstract public key(); abstract public next(); abstract public rewind(); abstract public valid(); } |
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]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class IteratorTest implements Iterator { private $total = 3; private $i = 1; public function current() { echo __METHOD__, "\n"; return $this->i; } public function key() { echo __METHOD__, "\n"; return $this->i; } public function next() { echo __METHOD__, "\n"; return ++$this->i; } public function rewind() { echo __METHOD__, "\n"; $this->i = 1; } public function valid() { echo __METHOD__, "\n"; $rtn = $this->i <= $this->total ? true : false; return $rtn; } } $object = new IteratorTest(); foreach($object as $key=>$value) { #echo $key, " = " , $x, "\n"; } |
Below is the output from this code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | IteratorTest::rewind IteratorTest::valid IteratorTest::current IteratorTest::key IteratorTest::next IteratorTest::valid IteratorTest::current IteratorTest::key IteratorTest::next IteratorTest::valid IteratorTest::current IteratorTest::key IteratorTest::next IteratorTest::valid |
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]