PHP - 从静态方法调用实例方法
我在从应用程序中的另一个类调用特定方法时遇到问题。我有一个 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 在
不牺牲当前工作流程的情况下执行此操作的更好方法是什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在
User
中创建一个Rest
实例:您还可以将
Rest
更改为单例并调用它的实例,但要注意这一点反模式。You can create a
Rest
instance inUser
:You could also change
Rest
to be a singleton and call an instance of it, but beware of this antipattern.您需要先创建一个实例。
You need to create an instance first.
正如错误消息所述,您没有在对象上下文中调用 send_response() 。
要么创建一个实例并调用该实例上的所有内容(恕我直言,以正确的方式),要么静态地执行所有操作,包括构造函数(您可能需要一个初始化方法)和属性。
You don't call send_response() in an object context, as the error message says.
Either you create an instance and call everything on that instance (IMHO the right way), or you do everything statically, including the constructor (you may want to have a intialization method instead) and the properties.