PHP - 迭代两次通用可迭代对象

PHP - Iterating twice a generic iterable

在 PHP 7.1 中有一个新的 iterable 伪类型,它抽象了数组和 Traversable 对象。

假设在我的代码中有一个 class 如下所示:

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