参考发电机不工作

Generator with reference not working

给定以下代码

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

此静态方法应在每次数组迭代时通过 ref 产生 $key => $value

然后我在另一个中使用静态方法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']));

我应该有一个 json 编码的字符串,但我总是有一个数组,我不明白为什么。

您需要确保传递引用"all the way through"

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

$arr$value