摘要:在PHP中,可以理解闭包是由匿名函数构成的一种“结构”。就像string,int等,可以把闭包函数作为变量的值来使用。PHP会自动把此种表达式转换成内置类 Closure 的对象实例。在上文中我有说道...
在PHP中,可以理解闭包是由匿名函数构成的一种“结构”。
就像string,int等,可以把闭包函数作为变量的值来使用。PHP会自动把此种表达式转换成内置类 Closure 的对象实例。
1.在上文中我有说道匿名函数(闭包函数)调用方式是 变量名() 其实就是调用了Closure类中的__invoke()方法,证明一下:$var = function ($name) {
return 'Hello ' . $name . '
';
};
echo $var->__invoke("yzmcms");
echo $var("yzmcms");
// 运行结果:
// Hello yzmcms
// Hello yzmcms
2.php闭包使用例子:class test{
private $_factory;
public function set($id, $value){
$this->_factory[$id] = $value;
}
public function get($id){
$value = $this->_factory[$id];
return $value();//如果不加括号,仅仅返回的是闭包类的一个对象,并不是user实例
}
}
class user{
private $_username;
function __construct($username = '') {
echo '我被实例化了
';
$this->_username = $username;
}
function get_username(){
return $this->_username;
}
}
$test = new test();
$test->set('zhangsan', function(){
return new user('张三');
});
$test->set('lisi', function(){
return new user('李四');
});
echo $test->get('zhangsan')->get_username();
echo '
';
echo $test->get('lisi')->get_username();
// 运行结果:
// 我被实例化了
// 张三
// 我被实例化了
// 李四
代码test类中有一个工厂($_factory)用来保存对象实例,然后通过set()方法注册服务,通过get()方法获取服务。
我们看到$test->set()的时候,使用了匿名函数,我们预先注册了zhangsan和lisi两个服务,这两个服务都是user类的实例,在$test->set的时候实际上并没有实例化,而是在$test->get()的时候才执行了匿名函数并将对象返回,这就实现了按需实例化,不用则不实例化,提高效率。