我试图从另一个类的PHP实例化一个类,并调用所述类的方法,但是无论我做什么,我都会收到错误。
为什么不能进行以下工作:
class Example {
public function sayHi () {
echo "hi";
}
}
class Caller {
private $_controller,
$_action;
public function __construct ($cont, $action) {
$this->_controller = $cont;
$this->_action = $action;
}
public function __toString() {
return (string)$this->_action;
}
public function run () {
$controller = new $this->_controller;
if (is_callable(array($controller, $this->_action))) {
$controller->$this->_action;
}
}
}
$caller = new Caller ('Example', 'sayHi');
$caller->run();
更改方法时,请执行以下工作?
public function run () {
$controller = new $this->_controller;
if (is_callable(array($controller, $this->_action))) {
call_user_func(array($this->_controller, $this->_action));
}
}
我不想要call_user_func的原因是因为它静态地调用了控制器。
删除魔术方法__toString给我:
Catchable fatal error: Object of class Caller could not be converted to string
再次添加将为我提供以下内容:
Undefined property: Example::$sayHi (same line, on method run() from Caller)
Trying to get property of non-object (same line, on method run() from Caller)
您部分正确。如果仅将类名和函数传递给call_user_func
它,则它将静态调用它。但是,如果将实例传递给它,它将在该实例内调用它。那就是可调用的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句