PHP-对泛型iterable迭代两次
在PHP7.1中有一种新的psudo类型,它抽象数组和可遍历的对象 假设在我的代码中有一个类,如下所示:PHP-对泛型iterable迭代两次,php,iterator,generator,iterable,Php,Iterator,Generator,Iterable,在PHP7.1中有一种新的psudo类型,它抽象数组和可遍历的对象 假设在我的代码中有一个类,如下所示: class Foo { private $iterable; public function __construct(iterable $iterable) { $this->iterable = $iterable; } public function firstMethod() { foreach
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
是一个数组或迭代器
,则可以正常工作,除非$iterable
是一个生成器
。实际上,在这种情况下,调用firstMethod()
然后调用secondMethod()
将产生以下异常:无法遍历已关闭的生成器
有没有办法避免此问题?发电机无法重新绕线。如果你想避免这个问题,你必须做一个新的发电机。如果您创建了一个实现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