<?PHPclassMyiteratorImplementsIterator {Private $position= 0; Private $array=Array( "Firstelement", "Secondelement", "Lastelement", ); Public function__construct () {$this->position = 0; } function Rewind() { Var_dump(__method__); $this->position = 0; } function Current() { Var_dump(__method__); return' One_ '.$this-Array[$this->position]. ' _two '; } function Key() { Var_dump(__method__); return $this-position; } function Next() { Var_dump(__method__); ++$this-position; } functionvalid () {Var_dump(__method__); return isset($this-Array[$this-position]); }}$it=NewMyiterator;foreach($it as $key=$value) { //var_dump ($key, $value); Echo $value; Echo"\ n";}
From the execution results above, the workflow of the iterator is this:
1. First point to array first
2. Determine whether it is valid
3. Get the current value
4. Get the current key
5. Enter the loop to perform the current pointer plus one operation
6. Whether the judgment is valid (invalid stop)
7. Get the current value
8. Get the current key
9. Repeat 5 Steps
Why use iterators?
In this example, the object is encapsulated to simplify the complexity of the foreach statement, or to focus on the process, while the details are given to the iterator.
The iterator itself is implemented through the C extension, so the traversal and PHP itself provided by the iterator is a performance difference of the second, because the traversal is an object rather than an array, we have encountered a lot of trouble in the traversal, even if we solve, there is no guarantee that we apply to the algorithm is the best
Iterators in PHP