致命错误:不在对象上下文中时使用$ 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 >
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 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
这篇关于致命错误:不在对象上下文中时使用$ this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!