I'm trying to instantiate a class from PHP from another class, as well as calling methods of said class, but no matter what I do, I recieve errors.
Why won't the following work:
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();
When changing the method run to the following works?
public function run () {
$controller = new $this->_controller;
if (is_callable(array($controller, $this->_action))) {
call_user_func(array($this->_controller, $this->_action));
}
}
The reason why I don't want call_user_func, is because it calls the controller statically.
Removing the magic method __toString gives me:
Catchable fatal error: Object of class Caller could not be converted to string
Adding it again gives me the following:
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)