gpt4 book ai didi

php - 带引用的发电机不工作

转载 作者:行者123 更新时间:2023-12-04 18:02:15 27 4
gpt4 key购买 nike

鉴于以下代码

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 编码的字符串,但我总是有一个数组,我不明白为什么。
  • questions $request var 中的属性不存在,它由魔术方法返回 __get ( questions 位于数组内部,因此该值由 __get 返回)
  • 如果我删除 generate 方法并给出 $questions对于我的 foreach,它可以工作,我有我的 json 编码字符串
  • 最佳答案

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

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

    对于两者 $arr$value

    关于php - 带引用的发电机不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33128979/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com