PHP - Iterating twice total repeatable
PHP 7.1 has a new iterable psudo type that abstracts arrays and objects Traversable
.
Suppose 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 great $iterable
- is it an array or Iterator
, except when it $iterable
is Generator
. In this case, it will actually call firstMethod()
and then secondMethod()
lead to the next one Exception: Cannot traverse an already closed generator
.
Is there a way to avoid this problem?
source to share
Generators cannot be rewound. If you want to avoid this problem, you need to create 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 that 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
source to share