Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/10869572/does-the-use-keyword-in-php-closures-pass-by-reference

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...