1 class myIterator implements Iterator { 2 private $position = 0; 3 private $array = array( 4 "first_element", 5 "second_element", 6 "last_element", 7 ); 8 9 public function __construct() { 10 $this->position = 0; 11 } 12 13 function rewind() { 14 var_dump(__METHOD__); 15 $this->position = 0; 16 } 17 18 function current() { 19 var_dump(__METHOD__); 20 return $this->array[$this->position]; 21 } 22 23 function key() { 24 var_dump(__METHOD__); 25 return $this->position; 26 } 27 28 function next() { 29 var_dump(__METHOD__); 30 ++$this->position; 31 } 32 33 function valid() { 34 var_dump(__METHOD__); 35 return isset($this->array[$this->position]); 36 } 37 } 38 39 $it = new myIterator; 40 41 foreach($it as $key => $value) { 42 echo '输出键值:'; 43 var_dump($key, $value); 44 //echo $key; 45 echo " "; 46 }
程序运行输出:
string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" 输出键值:int(0) string(13) "first_element" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" 输出键值:int(1) string(14) "second_element" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" 输出键值:int(2) string(12) "last_element" string(16) "myIterator::next" string(17) "myIterator::valid"
一般的迭代器内部需要下面的方法:
- Iterator::current — Return the current element 返回当前元素
- Iterator::key — Return the key of the current element 返回当前元素的键
- Iterator::next — Move forward to next element 移向下一个元素
- Iterator::rewind — Rewind the Iterator to the first element 重新回到第一个元素
- Iterator::valid — Checks if current position is valid 检查当前位置的有效性
如果不是很清楚迭代器的内容工作流程,可以查看下面的迭代器对数组的遍历过程:
/** * */ class MyIterator implements Iterator { private $var = array(); public function __construct($array) { if (is_array($array)) { $this->var = $array; } } public function rewind() { echo "倒回第一个元素 "; reset($this->var); } public function current() { $var = current($this->var); echo "当前元素: $var "; return $var; } public function key() { $var = key($this->var); echo "当前元素的键: $var "; return $var; } public function next() { $var = next($this->var); echo "移向下一个元素: $var "; return $var; } public function valid() { $var = $this->current() !== false; echo "检查有效性: {$var} "; return $var; } } $values = array(1,2,3); $it = new MyIterator($values); foreach ($it as $k => $v) { print "此时键值对 -- key $k: value $v "; }
程序运行结果:
倒回第一个元素 当前元素: 1 检查有效性: 1 当前元素: 1 当前元素的键: 0 此时键值对 -- key 0: value 1 移向下一个元素: 2 当前元素: 2 检查有效性: 1 当前元素: 2 当前元素的键: 1 此时键值对 -- key 1: value 2 移向下一个元素: 3 当前元素: 3 检查有效性: 1 当前元素: 3 当前元素的键: 2 此时键值对 -- key 2: value 3 移向下一个元素: 当前元素: 检查有效性: