在PHP中,闭包能否返回一个引用?

10

为了在PHP中从函数返回一个引用,必须:

...在函数声明和将返回值分配给变量时都使用引用运算符&。

最终看起来像这样:

function &func() { return $ref; }
$reference = &func();

我想从一个闭包中返回一个引用。在一个简化的例子中,我想要实现的是:

$data['something interesting'] = 'Old value';

$lookup_value = function($search_for) use (&$data) {
    return $data[$search_for];
}

$my_value = $lookup_value('something interesting');
$my_value = 'New Value';

assert($data['something interesting'] === 'New Value');

我似乎无法使用函数返回引用的常规语法。

1个回答

13

你的代码应该像这样:

$data['something interesting'] = 'Old value';

$lookup_value = function & ($search_for) use (&$data) {
    return $data[$search_for];
};

$my_value = &$lookup_value('something interesting');
$my_value = 'New Value';

assert($data['something interesting'] === 'New Value');

看看这个


一次就明白了。又一个奇怪的语法选择要记住。谢谢! - Sam Becker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接