【发布时间】: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
在不牺牲当前工作流程的情况下,有什么更好的方法来做到这一点。
【问题讨论】: