elite5472 elite5472 - 3 months ago 10
PHP Question

Does the use keyword in PHP closures pass by reference?

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
?

Answer

No, they are not passed by reference - the use follows a similar notation like the function's parameters. You can validate that on your own with the help of the debug_zval_dump function (Demo):

<?php
header('Content-Type: text/plain;');

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. 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();
}
Comments