Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...