spl_autoload_register在加载类时失败

时间:2016-01-13 15:08:10

标签: php spl-autoload-register

所以我的项目结构如下:

- Project
   - php
      - classes
          - Config.php
          - DB.php
      - core
          - init.php
      - index.php

在我的 core / init.php 文件中,我使用 spl_autoload_register()来加载不同的类:

spl_autoload_register(function ($class) {
    require_once 'classes/' .$class. '.php';
});

出于测试原因,在 index.php 中,我需要 init.php 文件并尝试我的数据库类的方法:

require_once 'php/core/init.php'; 
$_db = DB::getInstance();

但我什么都没得到。我确定问题是PHP,因为当我在 index.php 中只有html时,一切都有效。

问题出在哪里?我假设它来自 spl_autoload_register(),它无论如何都无法工作。

1 个答案:

答案 0 :(得分:3)

将自动加载器更改为:

spl_autoload_register(function ($class) {
    require_once __DIR__ . '/../classes/' .$class. '.php';
});

所以你确定它包含来自正确位置的文件。

相关问题