Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • The questions attribute in the $request var doesn't exist, it is returned by the magic method __get (questions is inside of an array so the value is returned by __get)
  • If I remove the generate method and give $questions to my foreach, it works and I have my json encoded string
like image 475
everytimeicob Avatar asked Oct 20 '25 09:10

everytimeicob


1 Answers

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

like image 61
Mark Baker Avatar answered Oct 21 '25 21:10

Mark Baker