无法在PHP中访问空属性

时间:2013-12-07 04:51:41

标签: php

尝试在另一个文件中创建实例时,我收到以下错误。我是PHP的新手,在我的代码中找不到任何语法错误。

致命错误:无法访问第21行/home/leondash/public_html/poll/classes/database.php中的空属性

class Database {

    private $host, $username, $password, $database;
    private $db;

    /** Opens a connection the database */
    public function __construct() {
            $this->host     = "localhost";
            $this->username = "dbuser";
            $this->password = "dbpass";
            $this->database = "dbname";

            // the following line is giving the error
            $this->db = mysqli_connect($this->host, $this->username, $this->$password, $this->database)
            or die('Error: Could not connect to the database');

            return true;
    }
}

2 个答案:

答案 0 :(得分:33)

第21行似乎有错误。更改:

$this->$password

为:

$this->password

修改

作为参考,这就是所谓的variable variable。例如:

$a = 'b';
$b = 'I am a variable variable';
echo $$a; // equivalent to `echo $b;` prints 'I am a variable variable'

答案 1 :(得分:1)

他们都是空的。

        $this->host     = "";
        $this->username = "";
        $this->password = "";
        $this->database = "";

你不能把这个网址称为“”。你不能拥有用户名“”。你不能拥有数据库“”。但可以输入密码“”。不推荐。