mar*_*osh 6 php iterator iterable generator
在 PHP 7.1 中,有一个新的可迭代伪类型,它抽象数组和Traversable对象。
假设在我的代码中我有一个如下所示的类:
class Foo
{
private $iterable;
public function __construct(iterable $iterable)
{
$this->iterable = $iterable;
}
public function firstMethod()
{
foreach ($this->iterable as $item) {...}
}
public function secondMethod()
{
foreach ($this->iterable as $item) {...}
}
}
Run Code Online (Sandbox Code Playgroud)
$iterable这在is 数组或 an时工作得很好Iterator,除非$iterable是 a Generator。事实上,在这种情况下,调用firstMethod()thensecondMethod()将产生以下结果Exception: Cannot traverse an already closed generator。
有办法避免这个问题吗?
发电机不能倒带。如果你想避免这个问题,你必须制作一个新的发电机。如果您创建一个实现 IteratorAggregate 的对象,这可以自动完成:
class Iter implements IteratorAggregate
{
public function getIterator()
{
foreach ([1, 2, 3, 4, 5] as $i) {
yield $i;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后只需传递该对象的实例作为迭代器:
$iter = new Iter();
$foo = new Foo($iter);
$foo->firstMethod();
$foo->secondMethod();
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
3
4
5
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)