Fatal error: Using $ this if not in the context of an explain context?
I am getting this weird error which I never had.
Fatal error: using $ this if not in object context
Chat.php (class)
<?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:
Chat::send(array(
'message' => Input::get('message'),
'author' => $user->data()->username,
'ts' => date('Y-m-d H:i:s')
));
An error message will appear.
source to share
You need to create an object with new
to be an object $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 a database connection until after the constructor is called, which is raised when used new
.
source to share
You access the send()
static
ally function (although it is not defined as such) using the operator ::
. Since you are using $this
in your function, it expects the object was created by a method __construct()
, but that doesn't happen in static function
. If you create a new instance of an object Chat
using $chat = new Chat($row)
, then it $this
will refer to this object in the function, which should be called using the operator ->
, as in $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 :
Because static methods are called without an instantiated object, the $ this pseudo-variable is not available inside a static method.
source to share