下面我们来了解如何实现一个自定义的迭代器,然后再开始慢慢理解迭代器的内部工作原理。先来看一个官方的例子:
01 | class myIterator implements Iterator { |
02 | private $position = 0; |
03 | private $array = array ( |
09 | public function __construct() { |
20 | return $this -> array [ $this ->position]; |
25 | return $this ->position; |
35 | return isset( $this -> array [ $this ->position]); |
41 | foreach ( $it as $key => $value ) { |
43 | var_dump( $key , $value ); |
程序运行输出:
01 | string(18) "myIterator::rewind" |
02 | string(17) "myIterator::valid" |
03 | string(19) "myIterator::current" |
04 | string(15) "myIterator::key" |
06 | string(13) "first_element" |
08 | string(16) "myIterator::next" |
09 | string(17) "myIterator::valid" |
10 | string(19) "myIterator::current" |
11 | string(15) "myIterator::key" |
13 | string(14) "second_element" |
15 | string(16) "myIterator::next" |
16 | string(17) "myIterator::valid" |
17 | string(19) "myIterator::current" |
18 | string(15) "myIterator::key" |
20 | string(12) "last_element" |
22 | string(16) "myIterator::next" |
23 | 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 检查当前位置的有效性
如果不是很清楚迭代器的内容工作流程,可以查看下面的迭代器对数组的遍历过程:
04 | class MyIterator implements Iterator |
06 | private $var = array (); |
08 | public function __construct( $array ) |
10 | if ( is_array ( $array )) { |
15 | public function rewind () { |
20 | public function current() { |
21 | $var = current( $this -> var ); |
26 | public function key() { |
27 | $var = key( $this -> var ); |
28 | echo "当前元素的键: $var\n" ; |
32 | public function next() { |
33 | $var = next( $this -> var ); |
34 | echo "移向下一个元素: $var\n" ; |
38 | public function valid() { |
39 | $var = $this ->current() !== false; |
40 | echo "检查有效性: {$var}\n" ; |
45 | $values = array (1,2,3); |
46 | $it = new MyIterator( $values ); |
48 | foreach ( $it as $k => $v ) { |
49 | print "此时键值对 -- key $k: value $v\n\n" ; |
程序运行结果:
06 | 此时键值对 -- key 0: value 1 |
13 | 此时键值对 -- key 1: value 2 |
20 | 此时键值对 -- key 2: value 3 |
现在就很清晰了吧?