PHP:数据库连接类 - 无法连接

时间:2012-03-28 04:20:15

标签: php mysql oop

我的DatabaseConnection课程出了问题。我似乎无法使$dbUser$dbName变量适用于此连接类。我目前必须手动将值放入引号中。有什么我做错了吗?

class DatabaseConnection {
    private $dbHost = "localhost";
    private $dbUser = "root";
    private $dbPass = "";
    private $dbName = "test";

    function __construct() {
        $connection = mysql_connect($dbHost, "root", $dbPass)
            or die("Could not connect to the database:<br />" . mysql_error());
        mysql_select_db("test", $connection) 
            or die("Database error:<br />" . mysql_error());
    }
}

如果您有改进现有课程的建议,请告诉我!

1 个答案:

答案 0 :(得分:2)

由于这是一个类,因此您必须使用$this->dbHost$this->dbUser等代替$dbHost$dbUser来访问类变量。 Php要求您对类变量使用$ this-&gt; variableName。

编辑:

这是你的代码,更改了mysql_connect变量以访问你的类变量

class DatabaseConnection {
    private $dbHost = "localhost";
    private $dbUser = "root";
    private $dbPass = "";
    private $dbName = "test";

    function __construct() {
        $connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
            or die("Could not connect to the database:<br />" . mysql_error());
        mysql_select_db("test", $connection) 
            or die("Database error:<br />" . mysql_error());
    }
}