关于闭包函数

class A {

public $name = 'xiaohei';

public function ceshi(){
    echo 'this is ceshi';
}

}

function test($a,$b){

var_dump($b);

}

test(1,function (){return (new A)->ceshi() ;});

对于闭包函数不是很了解,求大佬出来解释下,输出第二个参数为什么没有?
// 这是输出的结果 object(Closure)#1 (0) { } 我以为会输出 this is ceshi 呢

阅读 1.3k
1 个回答

和作用域有关系,你看下面的例子
e1


function test_1()
{
    $a = 'php';
    $func =  function ($b) use ($a)
    {
       // $a = 'java';
        echo $b.'_'.$a;
    };
    return $func;

}
$test = test_1();
$test('hello');

以上结果会输出 hello_php 那么可以看到 $a 被作为了变量 通过use传递给了 匿名函数 func 作为参数使用;如果去掉$a = 'java'的注释,那么以上结果会输出 hello_java

e2:将上面的函数改写为

function test_2()
{
    $a = 'php';
    $func =  function ($b) use ($a)
    {
       // $a = 'go';
        echo $b.'_'.$a;
    };
    $a = 'java';
    return $func;
}
$test = test_2();
$test('hello');

以上结果会输出 hello_php 说明在test_2中第二次为$a赋值的时候,并没有传递的到 func函数里面去。
同样的如果去掉 $a = 'go';那么以上结果会输出 hello_go

e3:现在为$a 加上引用

function test_3()
{
    $a = 'php';
    $func =  function ($b) use (&$a)
    {
        //$a = 'go';
        echo $b.'_'.$a;
    };
    $a = 'java';
    return $func;
}
$test = test_3();
$test('hello');

以上结果会输出 hello_java 说明在地址引用的时候 变量 a 的值会传递到 函数func里面去。
同样的如果去掉 $a = 'go';那么以上结果会输出 hello_go

以上三个简单的测试,很明白的说明的闭包里面参数的作用域。
在没有使用地址引用的时候 匿名函数的变量值,不会随着外部变量的改变而改变。(闭包的意义)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题