php - Anonymous function return value problem
phpcn_u1582
phpcn_u1582 2017-05-16 12:02:57
0
2
647
class A{}

class B{}
$a = function (){
    $a = new A();
    var_dump($a);
    return $a;
};

var_dump($a);
$b = $a(new B());

var_dump($b);

<strong>
输出:object(Closure)#1 (0) { } 
object(A)#3 (0) { } 
object(A)#3 (0) { }
</strong>


class A{}

class C{}
class B{
    public function run(){
     
        $b = function (){
            return new A();
        };
        var_dump($b);
        var_dump($this);
        return $b(new C());
    }
}
$b = new B();
var_dump($b->run());

输出:object(Closure)#2 (1) { ["this"]=> object(B)#1 (0) { } }
 object(B)#1 (0) { }
 object(A)#4 (0) { }

My question is, does passing in any object convert the closure object into the original object? Why is this happening?

I am at /a/11... and I wonder why the original object can be retrieved by passing in ($this).

phpcn_u1582
phpcn_u1582

reply all(2)
左手右手慢动作

Just take the first code segment as an example.
Are you wondering why the B object passed in completely disappeared when printed and turned into an A object?

Because although you $a(new B());了,但是匿名函数没接收啊,所以内部还是直接new A();

Execute this code and get a feel for it:

<?php
class A{}

class B{}

$a = function ($unknow = null){  //这里要接收的
    var_dump($unknow);
    return $unknow;
};

var_dump($a);

$b = $a(new B());

var_dump($b);
世界只因有你
class A{}
class C{}
class B{
    public function run(){
     
        $b = function (){
           var_dump(func_get_args());  //接收参数
            return new A();
        };
        var_dump($b);   //第一次输出 $b 闭包
        var_dump($this); //第二次输出 $this。  就是class B
        return $b(new C());
    }
}
$b = new B();
var_dump($b->run());   //第三次输出  是$b这个匿名函数的返回值 class A

$b(new C()) Your anonymous function $b does not accept parameters

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template