Iterator为php提供的生成器接口,实现该接口的下面几个方法后,就可以进行循环遍历。以下是生成器走的流程:
class Number implements Iterator
{
protected $i = 1;
protected $key;
protected $val;
protected $count;
public function __construct($count)
{
$this->count = $count;
echo "第{$this->i}步:对象初始化.</br>";
$this->i++;
}
public function rewind()
{
$this->key = 0;
$this->val = 0;
echo "第{$this->i}步:rewind()被调用.</br>";
$this->i++;
}
public function next()
{
$this->key += 1;
$this->val += 2;
echo "第{$this->i}步:next()被调用.</br>";
$this->i++;
}
public function current()
{
echo "第{$this->i}步:current()被调用.</br>";
$this->i++;
return $this->val;
}
public function key()
{
echo "第{$this->i}步:key()被调用.</br>";
$this->i++;
return $this->key;
}
public function valid()
{
echo "第{$this->i}步:valid()被调用.</br>";
$this->i++;
return $this->key < $this->count;
}
}
$number = new Number(5);
echo "start...</br>";
foreach ($number as $key => $value) {
echo "{$key} - {$value}</br>";
}
echo "...end...</br>";
输出的数据是:
第1步:对象初始化.
start...
第2步:rewind()被调用.
第3步:valid()被调用.
第4步:current()被调用.
第5步:key()被调用.
0 - 0
第6步:next()被调用.
第7步:valid()被调用.
第8步:current()被调用.
第9步:key()被调用.
1 - 2
第10步:next()被调用.
第11步:valid()被调用.
第12步:current()被调用.
第13步:key()被调用.
2 - 4
第14步:next()被调用.
第15步:valid()被调用.
第16步:current()被调用.
第17步:key()被调用.
3 - 6
第18步:next()被调用.
第19步:valid()被调用.
第20步:current()被调用.
第21步:key()被调用.
4 - 8
第22步:next()被调用.
第23步:valid()被调用.
...end...

被折叠的 条评论
为什么被折叠?



