Working principle
1. Before the first iteration, run the iterator::rewind() method.
Runs only once, returns the first element of the iterator, but the method has no return value
2. Verify whether the first element is valid.
Authentication methods can be customized. If the return value is true, execution continues; if the return value is false, the iteration terminates.
3. foreach continues to call Iterator.
Returns the key and value of the specified feature.
4. The method body of foreach
var_dump($key,$value)
5. After each iteration, call the Iterator to determine the next element and repeat the second step.
Example
string(18) "myIterator::rewind" //Call the rewind method before the iteration starts, return to the first element of the iterator, and execute $this->position = 1; string(17) "myIterator::valid" //Verify whether the current element $this->array[1] is valid, and continue execution if valid; string(19) "myIterator::current" // Return the value corresponding to the current element $this->array[0]='firstelement' string(15) "myIterator::key" // Returns the key of the current element $this->position = 1 int(1) //var_dump($key) string(12) "secondelement" //var_dump($value) string(16) "myIterator::next" //Move forward to the next element++$this->position=2 string(17) "myIterator::valid" //Verify whether the current element $this->array[2] is valid, and continue execution if valid; string(19) "myIterator::current" //Repeat the previous steps string(15) "myIterator::key" //Repeat the previous steps int(2) //Repeat the previous steps string(11) "lastelement" //Repeat the previous steps string(16) "myIterator::next" //Move forward to the next element++$this->position=3 string(17) "myIterator::valid" //Verify whether the current element $this->array[3] is valid, exit the traversal if it is invalid
The above is an analysis of the working principle of PHP iterator, I hope it will be helpful to everyone.