3
在PHP 7.1中有一个新的iterable psudo类型,它抽象出数组和Traversable
对象。PHP - 迭代两次泛型迭代
假设在我的代码我有一类这样的:
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
。
有没有办法避免这个问题?