在PHP中的类属性中存储闭包函数 [英] Storing a Closure Function in a Class Property in PHP
问题描述
确定我有下面的代码
<?php
class foo {
public $ bar = NULL;
public function boo(){
$ this-> bar();
}
}
$ mee = new foo();
//在属性上保存闭包函数
$ mee-> bar = function(){
echo'hahaha';
};
//使用类方法调用闭包函数
$ mee-> boo();
?>
,您可以看到它在这里运行 http://codepad.org/s1jhi7cv
现在我想要的是将闭合函数存储在类方法。
井关闭是可能的,因为我在这里阅读文档 http://php.net/manual/en/functions.anonymous.php
这是否可能?我做错了什么?请纠正我
codepad.org上的示例代码无效,因为codepad.org使用PHP 5.2.5,但是,你的代码也不能在支持闭包的PHP版本中工作,虽然你会得到一个不同的错误:
< http://codepad.viper-7.com/Ob0bH5\">http://codepad.viper-7.com/Ob0bH5
这是目前PHP的局限性。 $ obj-> member()
查找名为 member
的方法,并且不会查看属性,是可调用的。
我知道的唯一方法是让这个工作不需要 call_user_func()
/ call_user_func_array()
是:
public function boo b $ b $ func = $ this-> bar;
$ func();
}
ok I do have the code below
<?php
class foo{
public $bar = NULL;
public function boo(){
$this->bar();
}
}
$mee = new foo();
//save a closure function on the property
$mee->bar = function(){
echo 'hahaha';
};
//invoke the closure function by using a class method
$mee->boo();
?>
and you can see it running here http://codepad.org/s1jhi7cv
now what i want here is to store the closure function on the class method.
well closures are possible as i read the documentation about it here http://php.net/manual/en/functions.anonymous.php
is this possible? did i went to something wrong? please correct me
Your example code at codepad.org does not work because codepad.org uses PHP 5.2.5, and closure support was only added in 5.3.
However, your code will also not work in a PHP version that supports closures, although you will get a different error: http://codepad.viper-7.com/Ob0bH5
This is a limitation of PHP at present. $obj->member()
looks for a method named member
and will not look at properties to see if they are callable. It is, frankly, annoying.
The only way I am aware of to make this work without call_user_func()
/call_user_func_array()
is:
public function boo() {
$func = $this->bar;
$func();
}
这篇关于在PHP中的类属性中存储闭包函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!