Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
PHP - Iterating twice a generic iterable

In PHP 7.1 there is a new iterable psudo-type which abstracts arrays and Traversable objects.

Suppose that in my code I have a class like the following:

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) {...}
    }
}

This works fine is $iterable is an array or an Iterator, except when $iterable is a Generator. In that case in fact, calling firstMethod() and then secondMethod() would produce the following Exception: Cannot traverse an already closed generator.

Is there a way to avoid this issue?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Generators can't be rewound. If you want to avoid this issue, you have to make a new generator. This can be done automatically if you create an object that implements IteratorAggregate:

class Iter implements IteratorAggregate
{
    public function getIterator()
    {
        foreach ([1, 2, 3, 4, 5] as $i) {
            yield $i;
        }
    }
}

Then just pass an instance of this object as your iterator:

$iter = new Iter();
$foo = new Foo($iter);
$foo->firstMethod();
$foo->secondMethod();

Output:

1
2
3
4
5
1
2
3
4
5
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda