首页 > 解决方案 > 扩展类时找不到错误类

问题描述

我在一个名为 (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;

    }

  }

?>

分支.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";
      }

      }

    }

?>

标签: phpdatabaseclassoopextends

解决方案


您必须将“database.php”文件包含在“branch.php”文件的顶部

<?php include 'database.php'; ?>

另外,看看关于 php 的自动加载概念。https://www.php.net/manual/en/language.oop5.autoload.php


推荐阅读