【问题标题】:Generator with reference not working带参考的发电机不工作
【发布时间】:2016-01-12 18:10:01
【问题描述】:

给定以下代码

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

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

然后我在另一个类中使用静态方法:

$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 编码的字符串,但我总是有一个数组,我不明白为什么。

  • $request var 中的 questions 属性不存在,它由魔术方法 __get 返回(questions 在数组内部,因此值由 __get 返回)
  • 如果我删除 generate 方法并将 $questions 提供给我的 foreach,它可以工作并且我有我的 json 编码字符串

【问题讨论】:

    标签: php reference generator yield


    【解决方案1】:

    您需要确保“一直通过”引用传递

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

    $arr$value

    【讨论】:

    • 生成器和传递引用是古怪的,一般不推荐
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多