Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-对泛型iterable迭代两次_Php_Iterator_Generator_Iterable - Fatal编程技术网

PHP-对泛型iterable迭代两次

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

在PHP7.1中有一种新的psudo类型,它抽象数组和可遍历的对象

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

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