Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to return a reference from a closure in PHP?

Tags:

closures

php

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.

like image 959
Sam152 Avatar asked Jul 06 '13 08:07

Sam152


People also ask

How can I return multiple values from a function in PHP?

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.

What is a closure in PHP?

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.

What is a closure in PHP and why does it use the use identifier?

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.

How are closures established in PHP?

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.


1 Answers

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:

like image 135
hynner Avatar answered Sep 21 '22 17:09

hynner