Does the use keyword in PHP closures pass by reference?

function, functional-programming, php

Solution

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.

Problem

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`?

Original source