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

时间:2011-10-15 19:05:24

标签: php oop class object

我在应用中从另一个类调用特定方法时遇到问题。我有一个类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方法中收到致命错误:在不在对象上下文中时使用$ this

在不牺牲当前工作流程的情况下,更好的方法是做什么。

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

您需要先创建一个实例。

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

答案 2 :(得分:0)

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

您可以创建一个实例并调用该实例上的所有内容(恕我直言),也可以静态执行所有操作,包括构造函数(您可能希望使用初始化方法)和属性。

相关问题