dpf5207 2011-10-15 19:05
浏览 45
已采纳

PHP - 从静态方法调用实例方法

I am having trouble calling a specific method from another class in my app. I have a class, Rest, that determines various settings, etc. about a particular request received by the server and creates a Rest object with the properties of the request. The Rest class may then call any given method in a separate class to fulfill the request. The problem is that the other class needs to call methods in the Rest class to send a response, etc.

How can this be possible? Here's a blueprint of my current setup:

class Rest {
    public $controller = null;
    public $method = null;
    public $accept = null;

    public function __construct() {
        // Determine the type of request, etc. and set properties
        $this->controller = "Users";
        $this->method = "index";
        $this->accept = "json";

        // Load the requested controller
        $obj = new $this->controller;
        call_user_func(array($obj, $this->method));
    }

    public function send_response($response) {
        if ( $this->accept == "json" ) {
            echo json_encode($response);
        }
    }
}

The controller class:

class Users {
    public static function index() {
        // Do stuff
        Rest::send_response($response_data);
    }
}

This results in receiving a fatal error in the send_response method: Using $this when not in object context

What's the better way to do this without sacrificing the current workflow.

  • 写回答

3条回答 默认 最新

  • dozabt4329 2011-10-15 19:15
    关注

    You can create a Rest instance in User:

    public static function index() {
        // Do stuff
        $rest = new Rest;
        $rest::send_response($response_data);
    }
    

    You could also change Rest to be a singleton and call an instance of it, but beware of this antipattern.

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

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大