【问题标题】:PHP - Iterating twice a generic iterablePHP - 迭代两次通用迭代
【发布时间】: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,这很好用,除非$iterableGenerator。实际上,在这种情况下,调用firstMethod() 然后调用secondMethod() 会产生以下Exception: Cannot traverse an already closed generator

有没有办法避免这个问题?

【问题讨论】:

    标签: php iterator generator iterable


    【解决方案1】:

    发电机不能倒带。如果你想避免这个问题,你必须制作一个新的生成器。如果您创建一个实现 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-05
      • 2019-06-04
      • 2011-04-29
      • 2014-02-12
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多