代码来自:http ://php.net/manual/en/class.iterator.php(示例#1基本用法)
<?php
class myIterator implements Iterator {
private $position = 0;
private $array = array(
"firstelement",
"secondelement",
"lastelement",
);
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) {
var_dump($key, $value);
echo "\n";
}
?>
输出是:
string 'myIterator::rewind' (length=18)
string 'myIterator::valid' (length=17)
string 'myIterator::current' (length=19)
string 'myIterator::key' (length=15)
int 0
string 'firstelement' (length=12)
string 'myIterator::next' (length=16)
string 'myIterator::valid' (length=17)
string 'myIterator::current' (length=19)
string 'myIterator::key' (length=15)
int 1
string 'secondelement' (length=13)
string 'myIterator::next' (length=16)
string 'myIterator::valid' (length=17)
string 'myIterator::current' (length=19)
string 'myIterator::key' (length=15)
int 2
string 'lastelement' (length=11)
string 'myIterator::next' (length=16)
string 'myIterator::valid' (length=17)
所以我们可以看到:第一,function( var_dump(__METHOD__)
)输出的顺序是:
string 'myIterator::rewind' (length=18)
string 'myIterator::valid' (length=17)
string 'myIterator::current' (length=19)
string 'myIterator::key' (length=15)
2、3、函数输出顺序为:函数输出顺序为:
string 'myIterator::next' (length=16)
string 'myIterator::valid' (length=17)
string 'myIterator::current' (length=19)
string 'myIterator::key' (length=15)
4、函数输出顺序为:
string 'myIterator::next' (length=16)
string 'myIterator::valid' (length=17)
我的问题是:
- 有5个功能:
rewind();current(); key(); next(); valid();
为什么有些功能有时似乎不执行?myIterator::next
例如,我们在第一个函数输出中看不到。而且也rewind()
只显示一次。 - $array 中有 3 个值,所以假设 foreach 只运行了 3 次,但我们可以看到
string 'myIterator::valid' (length=17)
出现 4 次,为什么?