致命错误:在中不在对象上下文中时使用$this


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

我有这个类用于使用php/mysqli:连接到mysql数据库

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);
    }
}

现在,我有列表用户的任何页面:

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;

        }

现在,我看到这个错误:

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

如何修复此错误?!

正如错误所说,不能在类定义之外使用$this。要在类定义之外使用$_db,请首先将其设为public,而不是private:

public $_db

然后,使用以下代码:

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

--

你必须理解$this的实际含义。当在类定义中使用时,$this用于引用该类的对象。因此,如果您在AuthDB中有一个函数foo,并且您需要从foo中访问$_db,那么您将使用$this告诉PHP,您希望$_db来自foo所属的同一对象。

您可能想阅读这个StackOverflow问题:PHP:self vs$this