参考发电机不工作
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 编码的字符串,但我总是有一个数组,我不明白为什么。
- $request var 中的
questions
属性不存在,它由魔术方法 __get
返回(questions
在数组内部,因此返回值通过 __get)
- 如果我删除 generate 方法并将
$questions
赋给我的 foreach,它就会工作并且我有我的 json 编码字符串
您需要确保传递引用"all the way through"
public static function &generate(&$arr)
{
foreach ($arr as $key => &$value) {
yield $key => $value;
}
}
$arr
和 $value
给定以下代码
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 编码的字符串,但我总是有一个数组,我不明白为什么。
- $request var 中的
questions
属性不存在,它由魔术方法__get
返回(questions
在数组内部,因此返回值通过 __get) - 如果我删除 generate 方法并将
$questions
赋给我的 foreach,它就会工作并且我有我的 json 编码字符串
您需要确保传递引用"all the way through"
public static function &generate(&$arr)
{
foreach ($arr as $key => &$value) {
yield $key => $value;
}
}
$arr
和 $value