【发布时间】:2017-09-21 11:08:45
【问题描述】:
在 PHP 7.1 中有一个新的 iterable psudo-type 抽象数组和 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。
有没有办法避免这个问题?
【问题讨论】:
标签: php iterator generator iterable