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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:51:32  来源:igfitidea点击:

Fatal error: Using $this when not in object context in

phpmysqlmysqli

提问by B.B King

i have this class for connect to mysqldatabase 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 $thisoutside of the class definition. To use $_dboutside the class definition, first make it publicinstead 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 $thisactually means. When used inside a class definition, $thisis used to refer to an object of that class. So if you had a function fooinside AuthDB, and you needed to access $_dbfrom within foo, you would use $thisto tell PHP that you want the $_dbfrom the same object that foobelongs 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