Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Using $this when not in object context in [duplicate]

Tags:

php

mysql

mysqli

i have this class for connect to mysql database using php/mysqli:

class AuthDB {
    private $_db;

    public function __construct() {
        $this->_db = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME)
        or die("Problem connect to db. Error: ". mysqli_error());
    }

    public function __destruct() {
        $this->_db->close();
        unset($this->_db);
    }
}

now, i have any page for list user :

require_once 'classes/AuthDB.class.php';

session_start();

$this->_db = new AuthDB(); // error For This LINE
$query = "SELECT Id, user_salt, password, is_active, is_verified FROM Users where email = ?";
$stmt = $this->_db->prepare($query);

        //bind parameters
        $stmt->bind_param("s", $email);

        //execute statements
        if ($stmt->execute()) {
            //bind result columnts
            $stmt->bind_result($id, $salt, $pass, $active, $ver);

            //fetch first row of results
            $stmt->fetch();

            echo $id;


        }

now, i see this error:

Fatal error: Using $this when not in object context in LINE 6

How to fix this error?!

like image 810
B.B King Avatar asked Mar 31 '13 22:03

B.B King


1 Answers

Like the error says, you can't use $this outside of the class definition. To use $_db outside the class definition, first make it public instead of private:

public $_db

Then, use this code:

$authDb = new AuthDb();
$authDb->_db->prepare($query); // rest of code is the same

--

You have to understand what $this actually means. When used inside a class definition, $this is used to refer to an object of that class. So if you had a function foo inside AuthDB, and you needed to access $_db from within foo, you would use $this to tell PHP that you want the $_db from the same object that foo belongs to.

You might want to read this StackOverflow question: PHP: self vs $this

like image 162
Tushar Avatar answered Oct 02 '22 23:10

Tushar