PHP的Closure

姜旭
2023-12-01

PHP的Closure

参考博客

直接上代码最直接,看过效果之后就比较容易理解它是干什么的了。

class A
{
    private $name = '王力宏';
    protected $age = '30';
    private static $weight = '70kg';
    public $address = '中国';
    public static $height = '180cm';
}

试问,下面这段代码会不会出错:

$wrongFunction=function (){
    return A::$weight;
};

肯定会报错,因为$weigth是私有属性,只能在其类内部访问,那么可以在外部访问吗?可以,采用下面这种方法就行:

$private = function () {
    return self::$weight;
};
// 重点内容在这里
$weight = Closure::bind($private, null, A::class);

echo $weight();
// 70kg

在开始讲原理前,先说说Closure::bind方法3个参数的含义:

  1. 闭包函数的变量名
  2. 其中所使用到的对象实例。如果不需要实例,就传入null
  3. 实例对应的类名称

然后Closure::bind的作用就很简单了,就是将这个闭包函数放到实例对象中去,这样就可以访问到其中的privateprotected属性和方法了。

有了这个基础概念之后,就可以看一个更加简单的例子了:

$privateFunction = function () {
    // 注意看这里用的是 $this
    return $this->name ;
};

$name = Closure::bind($privateFunction, new A(), A::class);

echo $name().PHP_EOL;

这里将闭包函数$privateFunction塞进了类名为A::class的实例化类new A()中。


Closure的类实现原理我暂时还不知道,之后有机会再深入吧。

 类似资料: