【问题标题】:PHP - Calling instance method from static methodPHP - 从静态方法调用实例方法
【发布时间】:2011-10-15 19:05:24
【问题描述】:

我无法从我的应用程序中的另一个类调用特定方法。我有一个类,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 方法中收到一个致命错误:Using $this when not in object context

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

【问题讨论】:

    标签: php oop class object


    【解决方案1】:

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

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

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

    【讨论】:

    • 我想避免创建另一个 Rest 实例。我已经有一个 Rest 实例——在 Users 中调用 index() 的实例。如何再次访问该实例?
    • 将现有的Rest 对象作为参数传递给User::index()(或User 构造函数,或User::setRest() 方法等),然后可能调用$rest->send_response($response_data);。跨度>
    • 或者,使用单例。
    【解决方案2】:

    你需要先创建一个实例。

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 我没有在对象上下文中调用 send_response。问题不是调用 send_response,而是从 send_response 中访问原始 Rest 对象的对象属性。
      • 我就是这么说的。您不会在对象上下文中调用 send_response() 。执行此操作或使您的 send_response() 和属性静态并将构造函数更改为初始化函数:) 但恕我直言,正确的解决方案是创建一个实例并在对象上下文中调用它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2015-04-16
      相关资源
      最近更新 更多