everytimeicob
everytimeicob

Reputation: 327

Generator with reference not working

Given the following code

public static function &generate($arr)
{
    foreach ($arr as $key => $value) {
        yield $key => $value;
    }
}

This static method should yield $key => $value by ref on each array iteration

Then I use the static method in another class:

$questions = $request->questions;

foreach (self::generate($questions) as &$question) {
    $question['label'] = json_encode($question['label']);

    ... other code
}

unset($question);

die(var_dump($questions[0]['label']));

I should have a json encoded string but I always have an array, I don't understand why.

Upvotes: 4

Views: 390

Answers (1)

Mark Baker
Mark Baker

Reputation: 212452

You need to ensure pass-by-reference "all the way through"

public static function &generate(&$arr)
{
    foreach ($arr as $key => &$value) {
        yield $key => $value;
    }
}

for both $arr and $value

Upvotes: 2

Related Questions