PHP关闭中的use关键字是否通过引用传递? [英] Does the use keyword in PHP closures pass by reference?

查看:79
本文介绍了PHP关闭中的use关键字是否通过引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我这样做:

For example, if I do this:

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

$my_var = 0;
bar($my_var);

是否会修改 $ my_var ?如果没有,我怎样才能在不添加参数的情况下工作? $ foo

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

推荐答案

不,它们不是通过引用传递 - 使用遵循类似的函数的参数。您可以借助 debug_zval_dump 功能( Demo ):

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;

输出:

long(0) refcount(3)
0

通过所有范围工作的参考将有1的refcount。正如您所写,您通过将使用定义为传递引用来实现:

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

这篇关于PHP关闭中的use关键字是否通过引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆