下面我們來了解如何實現一個自定義的迭代器,然後再開始慢慢理解迭代器的內部工作原理。先來看一個官方的例子:
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 '輸出鍵值:'; var_dump($key, $value); //echo $key; echo "\n"; }
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"
一般的迭代器內部需要下面的方法:
如果不是很清楚迭代器的內容工作流程,可以查看下面的迭代器對數組的遍歷過程:
var = $array; } } public function rewind() { echo "倒回第一個元素\n"; reset($this->var); } public function current() { $var = current($this->var); echo "當前元素: $var\n"; return $var; } public function key() { $var = key($this->var); echo "當前元素的鍵: $var\n"; return $var; } public function next() { $var = next($this->var); echo "移向下一個元素: $var\n"; return $var; } public function valid() { $var = $this->current() !== false; echo "檢查有效性: {$var}\n"; return $var; } } $values = array(1,2,3); $it = new MyIterator($values); foreach ($it as $k => $v) { print "此時鍵值對 -- key $k: value $v\n\n"; }
倒回第一個元素 當前元素: 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 移向下一個元素: 當前元素: 檢查有效性: