失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > php 方法参数传递 在PHP中将实例方法作为参数传递

php 方法参数传递 在PHP中将实例方法作为参数传递

时间:2024-05-18 05:02:47

相关推荐

php 方法参数传递 在PHP中将实例方法作为参数传递

我想创建一个Listener类

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

我究竟做错了什么?

如果觉得《php 方法参数传递 在PHP中将实例方法作为参数传递》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。