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
。
有沒有辦法避免這個問題?