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.
PHP doesn't support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed.
A closure is an anonymous function that can access variables imported from the outside scope without using any global variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is defined. Closures can work around variable scope restrictions in a clean way.
A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure. use is early binding. That means the variable values are COPIED upon DEFINING the closure.
Basically a closure in PHP is a function that can be created without a specified name - an anonymous function. Here's a closure function created as the second parameter of array_walk() . By specifying the $v parameter as a reference one can modify each value in the original array through the closure function.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With