informatik-handwerk.de
informatik-handwerk.de

Reputation: 303

How can I find out if generator yields by-reference?

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();
}

Upvotes: 1

Views: 1052

Answers (1)

waterloomatt
waterloomatt

Reputation: 3742

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

Upvotes: 0

Related Questions