我是php新手,我想做的是在课堂外获取$ conn变量。
我从另一个文件中包含了这个文件并尝试使用$dbConfig->conn
来获取变量,但它什么也没有返回。
这是我在另一页上的通知。 注意:未定义的变量:第8行的C:\ xampp \ htdocs \ Chat \ login.php中的dbConfig
<?php
class dbConfig {
public $host;
public $username;
public $password;
public $dab;
public $conn;
public function dbConnect() {
$conn = mysqli_connect($this->host,$this->username,$this->password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully to server";
}
$db_selected = mysqli_select_db($conn, $this->dab);
if (!$db_selected) {
// if the given database doesn't exists
// creates new database with that name
$db_sql = 'CREATE DATABASE chatapp';
// verify the database is created
if (mysqli_query($conn, $db_sql)){
echo "Database chatapp already exists or created successfully\n";
} else {
echo 'Error creating database: ' . mysqli_error() . "\n";
}
}
// creating tables
$table_sql = "CREATE TABLE IF NOT EXISTS users (".
"uid INT PRIMARY KEY AUTO_INCREMENT,".
"username VARCHAR(30) UNIQUE,".
"password VARCHAR(50),".
"name VARCHAR(100),".
"email VARCHAR(70) UNIQUE); ";
// verify the table is created
if (mysqli_query($conn, $table_sql)) {
echo "Table: users already exists or created successfully\n";
} else {
echo 'Error creating table: ' . mysqli_error($table_sql) . "\n";
}
}
}
$obj = new dbConfig();
$obj->host = 'localhost';
$obj->username = 'root';
$obj->password = '';
$obj->dab = 'chatapp';
$obj->dbConnect();
答案 0 :(得分:0)
$obj
而非$dbConfig
,因此请使用$obj
$conn
指定为对象属性$this->conn = mysqli_connect($this->host,$this->username,$this->password);
然后在课程中使用$this->conn
。
答案 1 :(得分:0)
问题是你如何在方法中引用类变量。看:
public function dbConnect() {
$conn = mysqli_connect($this->host,$this->username,$this->password);
...
在这里,您要创建一个名为$conn
的局部变量(仅限于当前方法的范围)。由于您正在使用该课程的实例,因此您需要使用$this
访问您的班级成员:
$this->conn = mysqli_connect(...);
请查看the docs了解更多信息。