問題描述
我有這個類用于使用 php
/mysqli
連接到 mysql
數據庫:
class AuthDB {私人 $_db;公共函數 __construct() {$this->_db = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME)or die("連接數據庫有問題.錯誤:".mysqli_error());}公共函數 __destruct() {$this->_db->close();未設置($this->_db);}}
現在,我有列表用戶的任何頁面:
require_once 'classes/AuthDB.class.php';session_start();$this->_db = new AuthDB();//這條線的錯誤$query = "SELECT Id, user_salt, password, is_active, is_verified FROM Users where email = ?";$stmt = $this->_db->prepare($query);//綁定參數$stmt->bind_param("s", $email);//執行語句如果 ($stmt->execute()) {//綁定結果列$stmt->bind_result($id, $salt, $pass, $active, $ver);//獲取第一行結果$stmt->fetch();回聲 $id;}
現在,我看到這個錯誤:
致命錯誤:第 6 行中不在對象上下文中時使用 $this
如何修復這個錯誤?!
就像錯誤所說的那樣,您不能在類定義之外使用 $this
.要在類定義之外使用 $_db
,首先將其設為 public
而不是 private
:
public $_db
然后,使用此代碼:
$authDb = new AuthDb();$authDb->_db->prepare($query);//其余代碼相同
--
您必須了解 $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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!