我有如下 php 代码:
class Foo {
public $anonFunction;
public function __construct() {
$this->anonFunction = function() {
echo "called";
}
}
}
$foo = new Foo();
//First method
$bar = $foo->anonFunction();
$bar();
//Second method
call_user_func($foo->anonFunction);
//Third method that doesn't work
$foo->anonFunction();
php 中有没有一种方法可以使用第三种方法来调用定义为类属性的匿名函数?
thanks
不直接。$foo->anonFunction();
不起作用,因为 PHP 将尝试直接调用该对象上的方法。它不会检查名称的属性是否存储可调用对象。不过,您可以拦截方法调用。
将其添加到类定义中
public function __call($method, $args) {
if(isset($this->$method) && is_callable($this->$method)) {
return call_user_func_array(
$this->$method,
$args
);
}
}
该技术也有解释
- JavaScript 风格的对象字面量 http://www.phpied.com/javascript-style-object-literals-in-php/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)