Let's look at how to implement a custom iterator and then begin to understand how the iterator works internally. Let's take a look at an official example:
Class Myiterator implements Iterator { private $position = 0; Private $array = Array (tri-Live Casino "First_element", "Second_element", "Last_element", ); Public Function __construct () { $this->position = 0; } Function Rewind () { var_dump (__method__); $this->position = 0; } function current () { var_dump (__method__); return $this->array[$this->position]; } Function key () { var_dump (__method__); return $this->position; } function Next () { var_dump (__method__); + + $this->position; } function valid () { var_dump (__method__); return Isset ($this->array[$this->position]);} } $it = new Myiterator;foreach ($it as $key = + $value) {echo ' output key value: '; Var_dump ($key, $value);//echo $key; echo "\ n";}
Program Run output:
String "Myiterator::rewind" string (myiterator::valid) "Myiterator::current" string (15) " Myiterator::key "Output key value: Int (0) string (" First_element "string ()" Myiterator::next "string (" Myiterator::valid ") String ("Myiterator::current" string "Myiterator::key" Output key value: Int (1) string "Second_element" string (16) " Myiterator::next "string (myiterator::valid)" string "Myiterator::current" string ("Myiterator::key") Output key value: Int (2) string (last_element) "Myiterator::next" string (+) "Myiterator::valid"
The following method is required inside a generic iterator:
- Iterator::current-return the current element returns
- Iterator::key-return the key of the current element returns the keys
- Iterator::next-move forward to next element moves to the next
- Iterator::rewind-rewind the Iterator to the first element again
- Iterator::valid-checks If position is valid check the validity of the current location
If the content workflow of the iterator is not clear, you can view the following iterator traversal of the array:
/*** @author Concise Modern Magic Http://www.nowamagic.net*/class Myiterator implements iterator{private $ var = array (); Public function __construct ($array) {if (Is_array ($array)) {$this->var = $array; }} Public Function rewind () {echo "rewind the first element \ n"; Reset ($this->var); The public Function current () {$var = current ($this->var); echo "current element: $var \ n"; return $var; Public Function key () {$var = key ($this->var); echo "Key of current element: $var \ n"; return $var; Public function Next () {$var = next ($this->var); echo "moves to the next element: $var \ n"; return $var; Public Function Valid () {$var = $this->current ()!== false; echo "Check validity: {$var}\n"; return $var; }} $values = Array (n/a), $it = new Myiterator ($values), foreach ($it as $k + = $v) {print "At this time key-value pair-key $k: Value $v \ nthe ";}
Program Run Result:
It's clear now, isn't it?
Look at the internal execution of the PHP iterator