【问题标题】:Fatal error: Class 'conn' not found when it's there致命错误:存在时找不到类“conn”
【发布时间】:2020-01-18 22:09:21
【问题描述】:

我是 OOP php 新手,谁能解释一下问题出在哪里:

包括/autoloader.inc.php:

<?php
spl_autoload_register('autoloader');
function autoloader($class) {
  $path = "class/";
  $extension = ".class.php";
  $fullPath = $path . $class . $extension;
  if (!file_exists($fullPath))
    return false;
  include_once $fullPath;
}
?>

然后是 index.php:

<?php
include 'include/autoloader.inc.php';
$conn = new conn();
// $user = new user();
?>

和类/user.class.php:

class conn {}
class user extends conn {}

我尝试做 get_declared_classes():
- 在声明 $conn 或 $users 之前,未列出类 conn 和 users。
- 如果我声明 $conn,我会从主题中得到致命错误。
- 如果我只声明 $users 并执行 get_declared_classes(),则两个类都会列出。

【问题讨论】:

  • class conn {}class/user.class.php?
  • @AlexHowansky 我不知道我做了什么,但现在它正在工作......谢谢!
  • "conn 和 user 类都在 class/user.class.php 中" 当 PHP 遇到 new conn() 时,你的自动加载器会触发,并在 @987654327 中查找类@,失败了。通过将conn 放入class/conn.class.phpuser 放入class/user.class.php,使您的代码符合您的自动加载器的期望。

标签: php class oop


【解决方案1】:

当您声明 new user() 时,会列出这两个类,因为您的自动加载器文件只包含 user 类而不包含 conn 类。这就是您的 autloader 类的编写方式。

也许您可以为您的类创建单独的文件并以这种方式加载它们!

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 2011-09-08
    • 2011-12-17
    • 2018-12-21
    • 2012-11-21
    • 2015-03-20
    • 2015-03-28
    • 2014-03-13
    相关资源
    最近更新 更多