匿名函数


class A
{
    public $base = 100;
    public function __construct()
    {
        echo "a-->construct";
    }
}
class B
{
    private $base = 1000;
    public function __construct()
    {
        echo "b-->construct";
    }
}
class C
{
    private static $base = 10000;
    public function __construct()
    {
        echo "c-->construct";
    }
}
$f = function () {
    return $this->base + 3;
};
$sf = static function () {
    return self::$base + 3;
};

//bind(function,object ,newscope ='static') 这个方法是 Closure::bindTo() 的静态版本
//function Closure 需要绑定的匿名函数。
//object 需要绑定到匿名函数的对象,或者 NULL 创建未绑定的闭包。
//newscop 类作用域,用来决定在闭包中 $this 对象的 私有、保护方法 的可见性
$a = Closure::bind($f, new A);
print_r($a());
echo PHP_EOL;
$b = Closure::bind($f, new B, 'B');
print_r($b());
echo PHP_EOL;

//bindTo
$c = $sf->bindTo(null, 'C');
print_r($c());
echo PHP_EOL;
exit;

输出结果

  a-->construct103 b-->construct1003 10003

c中并没有触发构造函数。
感觉其实跟trait类很像。但是匿名函数的绑定可以绑定,也可以取消绑定。
原文地址:https://www.cnblogs.com/buerr/p/8268424.html