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

时间:2013-03-31 22:04:01

标签: 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);
    }
}

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

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

如何解决此错误?!

1 个答案:

答案 0 :(得分:6)

与错误一样,您不能在类定义之外使用$this。要在类定义之外使用$_db,请首先将其设为public而不是private

public $_db

然后,使用此代码:

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

-

您必须了解$this实际意味着什么。在类定义中使用时,$this用于引用该类的对象。因此,如果您在foo内有AuthDB函数,并且需要从$_db内访问foo,则可以使用$this告诉PHP您想要的来自$_db所属的同一对象的foo

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