46

For example, if I do this:

function bar(&$var) { $foo = function() use ($var) { $var++; }; $foo(); } $my_var = 0; bar($my_var); 

Will $my_var be modified? If not, how do I get this to work without adding a parameter to $foo?

0

3 Answers 3

73

No, they are not passed by reference - the use follows a similar notation like the function's parameters.

As written you achieve that by defining the use as pass-by-reference:

 $foo = function() use (&$var) 

It's also possible to create recursion this way:

$func = NULL; $func = function () use (&$func) { $func(); } 

NOTE: The following old excerpt of the answer (Jun 2012) was written for PHP < 7.0. As since 7.0 (Dec 2015) the semantics of debug_zval_dump() changed (different zval handling) the refcount(?) output of it differs nowadays and are not that much saying any longer (integers don't have a refcount any longer).

Validation via the output by not displaying $my_var changed (from 0) still works though (behaviour).

You can validate that on your own with the help of the debug_zval_dump function (Demo):

function bar(&$var) { $foo = function() use ($var) { debug_zval_dump($var); $var++; }; $foo(); }; $my_var = 0; bar($my_var); echo $my_var; 

Output:

long(0) refcount(3) 0 

A full-through-all-scopes-working reference would have a refcount of 1.

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

1 Comment

Better a year later than never!
21

Closures are, almost by definition, closed by value, not by reference. You may "use by reference" by adding an & in the argument list:

function() use (&$var) 

This can be seen in example 3 in the anonymous functions manual page.

Comments

4

No, they are not passed by reference.

function foo(&$var) { $foo = function() use ($var) { $var++; }; $foo(); } $my_var = 0; foo($my_var); echo $my_var; // displays 0 function bar(&$var) { $foo = function() use (&$var) { $var++; }; $foo(); } $my_var = 0; bar($my_var); echo $my_var; // displays 1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.