10

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 Answer 1

13

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Got it in one. Another bizarre choice of sytax to remember. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.