我想创建一个监听器类
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
callable
的类型,因此,如果将其用作类型提示,则表示“名为callable
的类”。如果使用PHP> = 5.4,则callable
是有效的提示。 public function add(callable $function)
public function add($function)
$listener->add(array($this, 'bar'));
关于php - 在PHP中将实例方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13543143/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) | Powered by Discuz! X3.4 |