迭代器实现代码
<?php class myIterator implements Iterator { public $position = 0 ; public $arr = array('one','two','three','four','five','six'); public function __construct() { $this->position = 0; } public function rewind() { var_dump(__METHOD__); $this->position = 0 ; } public function current() { var_dump(__METHOD__); return $this->arr[$this->position] ; } public function key() { var_dump(__METHOD__); return $this->position; } public function next() { var_dump(__METHOD__); ++$this->position; } public function valid() { var_dump(__METHOD__); return isset($this->arr[$this->position]); } } $it = new myIterator; foreach($it as $key=>$value) { var_dump($key,$value); echo "</br>"; }
遍历迭代器时内部执行流程
string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(0) string(3) "one" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(1) string(3) "two" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(2) string(5) "three" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(3) string(4) "four" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(4) string(4) "five" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(5) string(3) "six" string(16) "myIterator::next" string(17) "myIterator::valid"