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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器