I am programming a generic component which wraps a generator and does routine manipulation:
To emulate the wrapped generator as close as possible, I want to use references if the generator is using references.
When I try to iterate a non-reference generator using foreach ($generator as $key => &$value)
methodology, I receive the following error:
You can only iterate a generator by-reference if it declared that it yields by-reference
Is there a way to find out, if the generator at hand is returning references? I did not have success using reflection:
$reflectedGeneratorValueSupplier = new \ReflectionMethod($generator, 'current');
$this->canReference = $reflectedGeneratorValueSupplier->returnsReference(); //always false
Also, iterating generator without using foreach
construct does not work at all with references:
while ($generator->valid()) {
$key = $generator->key();
$value =& $generator->current(); //error, only variables can be passed by reference
$generator->next();
}
Using ReflectionGenerator and then getFunction seems to work.
http://sandbox.onlinephpfunctions.com/code/92ed79dc7a6e925243f0c55898a5d1170f994189
<?php
function &generate(&$arr)
{
foreach ($arr as $key => &$value) {
yield $key => $value;
}
};
$input = range(0,100);
$generator = generate($input);
$r = new ReflectionGenerator ($generator);
var_dump($r->getFunction()->returnsReference()); // true