致命错误:使用$这个时候不是在目标范围内[复制](Fatal error: Using $this

2019-08-18 11:09发布

这个问题已经在这里有一个答案:

  • 致命错误:使用$这不是在对象上下文时 4个回答

我有这个类连接到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

如何解决这个错误?

Answer 1:

像错误说,你不能使用$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:自我VS $此



文章来源: Fatal error: Using $this when not in object context in [duplicate]
标签: php mysql mysqli