我想创建一个监听器类 class Listener {
var $listeners = array();
public function add(callable $function) {
$this->listeners[] = $function;
}
public function fire() {
foreach($this->listeners as $function) {
call_user_func($function);
}
}
}
class Foo {
public function __construct($listener) {
$listener->add($this->bar);
}
public function bar() {
echo 'bar';
}
}
$listener = new Listener();
$foo = new Foo($listener);
但是此代码因以下错误而失败:
Notice: Undefined property: Foo:bar in index.php on line 18
Catchable fatal error: Argument 1 passed to Listener::add() must be callable, null given, called in index.php on line 18 and defined index.php on line 5
我究竟做错了什么?
Best Answer-推荐答案 strong>
在PHP 5.4之前,没有名为callable 的类型,因此,如果将其用作类型提示,则表示“名为callable 的类”。如果使用PHP> = 5.4,则callable 是有效的提示。 可调用对象由描述可调用对象名称的字符串(例如函数名称或类方法名称)或数组指定,其中第一个元素是对象的实例,第二个元素是要调用的方法的名称叫做。 对于PHP <5.4,请替换
public function add(callable $function)
和:
public function add($function)
调用它:
$listener->add(array($this, 'bar'));
关于php - 在PHP中将实例方法作为参数传递,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/13543143/
|