我的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());
}
}
如果您有改进现有课程的建议,请告诉我!
答案 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());
}
}