2

I'm getting this strange error which I have never got before.

Fatal error: Using $this when 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')
));

The error pops up.

Gustaf Gunér
  • 2,272
  • 4
  • 17
  • 23
  • You need to intantiate a Chat object (passing your database connection into the constructor) before you can call the send() method, because it isn't a static method – Mark Baker May 03 '14 at 00:33
  • `$this` is the object that was used in a call like `$object->send()`. You didn't apply the method to an object, what do you expect `$this` to be? – Barmar May 03 '14 at 00:38

2 Answers2

0

You need to create an object with new, so that there will be a $this object:

$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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You are accessing the send() function statically (although it is not defined as such) by using the operator ::. 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. 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().

// 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 callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

doublesharp
  • 26,888
  • 6
  • 52
  • 73