php 致命错误:不在对象上下文中时使用 $this
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15735099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fatal error: Using $this when not in object context in
提问by B.B King
i have this class for connect to mysql
database using php
/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);
}
}
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?!
如何修复这个错误?!
回答by Tushar
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
:
就像错误所说的那样,您不能$this
在类定义之外使用。要$_db
在类定义之外使用,首先使用它public
而不是private
:
public $_db
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.
你必须明白什么$this
是真正的意思。在类定义$this
中使用时,用于引用该类的对象。因此,如果您在foo
内部有一个函数AuthDB
,并且您需要$_db
从内部访问foo
,您将使用$this
告诉 PHP 您想要$_db
来自foo
属于同一对象的。
You might want to read this StackOverflow question: PHP: self vs $this
你可能想阅读这个 StackOverflow 问题:PHP: self vs $this