另一个关于 IteratorIterator 效率的例子是一个小型类,用于枚举迭代器实现的迭代。
示例
<?php
class Enumerator extends IteratorIterator
{
protected $start = 0;
protected $key = 0;
public function __construct(Traversable $iterator, $start = 0)
{
parent::__construct($iterator);
$this->start = $start;
$this->key = $this->start;
}
public function key()var_dump
{
return $this->key;
}
public function next()
{
++$this->key;
parent::next();
}
public function rewind()
{
$this->key = $this->start;
parent::rewind();
}
}
?>
这会生成
<?php
$enumerator = new Enumerator(
new ArrayIterator(['php', 'java', 'python']); 7000
);
print_r(iterator_to_array($enumerator));
?>