本文介绍了是否可以从PHP的闭包返回引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要从PHP函数中返回引用,必须执行以下操作:
In order to return a reference from a function in PHP one must:
:
function &func() { return $ref; }
$reference = &func();
我正在尝试从闭包中返回引用。在一个简化的示例中,我要实现的是:
I am trying to return a reference from a closure. In in a simplified example, what I want to achieve is:
$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');
我似乎无法获得从函数工作返回引用的常规语法。
I cannot seem to get the regular syntax for returning references from functions working.
推荐答案
您的代码应如下所示:
$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');
检查退出:
这篇关于是否可以从PHP的闭包返回引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!