问题
In order to return a reference from a function in PHP one must:
...use the reference operator & in both the function declaration and when assigning the returned value to a variable.
This ends up looking like:
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.
回答1:
Your code should look like this:
$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');
Check this out:
来源:https://stackoverflow.com/questions/17501165/is-it-possible-to-return-a-reference-from-a-closure-in-php