[英]Fatal error: Using $this when not in object context explanation?
I'm getting this strange error which I have never got before. 我遇到了从未有过的奇怪错误。
Fatal error: Using $this when not in object context
致命错误:不在对象上下文中时使用$ this
Chat.php (class) Chat.php(类)
<?php
class Chat {
private $_data = array(),
$_db;
public function __construct($row){
$this->_db = DB::getInstance();
$this->_data = $row;
}
public function send($fields = array()) {
$this->_db->insert('messages', $fields); <------- ERROR
}
When I call the send function like this: 当我这样调用send函数时:
Chat::send(array(
'message' => Input::get('message'),
'author' => $user->data()->username,
'ts' => date('Y-m-d H:i:s')
));
The error pops up. 错误弹出。
You need to create an object with new
, so that there will be a $this
object: 您需要使用
new
创建一个对象,以便有一个$this
对象:
$chat = new Chat($row);
$chat->Send(array(
'message' => Input::get('message'),
'author' => $user->data()->username,
'ts' => date('Y-m-d H:i:s')
));
You don't create the database connection until the constructor is called, which happens when new
is used. 在调用构造函数之前,您不会创建数据库连接,这在使用
new
时发生。
You are accessing the send()
function static
ally (although it is not defined as such) by using the operator ::
. 您正在使用操作符
::
static
访问send()
函数(尽管它没有这样定义)。 Because you are using $this
in your function, it expects an object to have been created by the __construct()
method, but this does not happen in a static function
. 因为您在函数中使用
$this
,所以它期望通过__construct()
方法创建一个对象,但这在static function
中不会发生。 If you create a new instance of the Chat
object using $chat = new Chat($row)
then $this
will refer to that object in the function, which should be called using the ->
operator as in $chat->send()
. 如果使用
$chat = new Chat($row)
创建Chat
对象的新实例,则$this
将引用函数中的该对象,应使用->
运算符调用该对象,如$chat->send()
。
// Create a new Chat object using __construct( $row ), creating $this
$chat = new Chat( $row );
// Call send() method on the $chat object
$chat->send( array() ); // add your data
See the documentation for the static keyword : 请参阅文档以了解static关键字 :
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
由于无需创建对象实例即可调用静态方法,因此伪变量$ this在声明为static的方法内部不可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.