duanguochong0397 2014-01-10 19:39
浏览 28
已采纳

非静态地从另一个类调用类和方法

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)
  • 写回答

2条回答 默认 最新

  • dongwei5740 2014-01-10 19:44
    关注

    You're partially right. If you simply pass a class name and function to call_user_func it will call it statically. But if you pass an instance to it, it will call it within that instance. That's what callables are.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错