【问题标题】:Error class not found when I extends a class [duplicate]扩展类时找不到错误类[重复]
【发布时间】: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";
      }

      }

    }

?>

【问题讨论】:

标签: php database class oop extends


【解决方案1】:

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

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

另外,看看 autoload 概念与 php。 https://www.php.net/manual/en/language.oop5.autoload.php

【讨论】:

    【解决方案2】:

    你需要使用 require() 或 include() 调用 branch.php 中的 database.php 文件(因为 Branch Class 不知道 Database Class 存在) - 取决于。 第二个选项是使用命名空间和“使用”语句以便于进一步开发。 https://www.php.net/manual/en/language.namespaces.php

    【讨论】:

      【解决方案3】:

      你应该这样做 require_once('database.php');从父类继承类实体。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-11
        • 2017-07-28
        • 1970-01-01
        • 2019-11-20
        • 2019-12-06
        • 2012-08-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多