【发布时间】:2020-06-01 13:29:07
【问题描述】:
我在一个名为 (classes) 的目录中有两个文件,其中包含类,第一个用于构建连接到数据库的主类 (Database)。 第二个(Branch)扩展了从数据库中获取数据的 Database 类。
当我尝试运行“getBranch”函数时,我收到一条错误消息:
未捕获的错误:在 C:\xampp\htdocs\branches\classes\branch.php 中找不到类“数据库”
请在下面找到代码并告知需要什么。
数据库.php:
<?php
class Database {
private $host;
private $user;
private $pwd;
private $dbName;
public $conn;
public function connect() {
$this->host = "localhost";
$this->user = "root";
$this->pwd = "";
$this->dbName = "branchs";
//create connection
$conn = new mysqli($this->host, $this->user, $this->pwd, $this->dbName);
//chech connection
if ($conn->connect_error) {
die("Connection failed :" . $conn->connect_error);
} else {
echo "Success";
}
return $conn;
}
}
?>
branch.php:
<?php
class Branch extends Database {
public function getBranch() {
$sql = "SELECT * FROM branches";
$result = $this->connect()->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name :" . $row['brName'] . "City :" . $row['brCity'] . "<br>";
}
} else {
echo "0 results";
}
}
}
?>
【问题讨论】:
-
你如何尝试运行“getBranch”函数?你实例化了
Branch类的对象吗? -
需要考虑的事情 - stackoverflow.com/questions/7827713/…
-
使用此代码您也将很快耗尽连接。
-
在 Internet 上进行简单搜索很可能会避开这个问题。
标签: php database class oop extends