在 PHP 7.1 中有一个新的 iterable抽象数组和 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) {...}
}
}
如果 $iterable
是一个数组或一个 Iterator
,这很好用,除非 $iterable
是一个 Generator
。事实上,在那种情况下,调用 firstMethod()
然后调用 secondMethod()
会产生以下 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;
}
}
}
然后只需将此对象的一个实例作为迭代器传递:
$iter = new Iter();
$foo = new Foo($iter);
$foo->firstMethod();
$foo->secondMethod();
输出:
1
2
3
4
5
1
2
3
4
5
关于PHP - 迭代两次通用迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43593670/