从静态方法调用实例方法


PHP - Calling instance method from static method

我在我的应用程序中从另一个类调用特定方法时遇到了麻烦。我有一个类,Rest,它确定了关于服务器收到的特定请求的各种设置等,并创建了一个带有请求属性的Rest对象。然后Rest类可以调用单独类中的任何给定方法来完成请求。问题是其他类需要调用Rest类中的方法来发送响应,等等。

这怎么可能?这是我当前设置的蓝图:

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);
        }
    }
}

控制器类:

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

这会导致在send_response方法中收到一个致命错误:

在不牺牲当前工作流程的情况下,有什么更好的方法来做到这一点?

可以在User中创建一个Rest实例:

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

您也可以将Rest更改为单例并调用它的实例,但要注意此反模式

您需要先创建一个实例。

class Users {
    public static function index() {
        // Do stuff
        $rest = new Rest();
        $rest->send_response($response_data);
    }
}

您没有在对象上下文中调用send_response(),如错误消息所示。

您可以创建一个实例并调用该实例上的所有内容(IMHO正确的方式),或者您静态地执行所有内容,包括构造函数(您可能希望有一个初始化方法代替)和属性。