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

B.B*_*ing 5 php mysql mysqli

我有这个类mysql使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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;


        }
Run Code Online (Sandbox Code Playgroud)

现在,我看到这个错误:

Fatal error: Using $this when not in object context in LINE 6
Run Code Online (Sandbox Code Playgroud)

如何解决这个错误?!

Tus*_*har 6

就像错误说的那样,你不能$this在类定义之外使用.要$_db在类定义之外使用,首先要使用它public而不是private:

public $_db

然后,使用此代码:

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

-

你必须明白$this实际意味着什么.在类定义$this中使用时,用于引用该类的对象.因此,如果你有一个函数foo在内部AuthDB,并且你需要$_db从内部访问foo,你会用$thisPHP告诉PHP你想要$_db来自同一个对象foo.

您可能想要阅读此StackOverflow问题:PHP:self vs $ this