【问题标题】:spl_autoload_reqister classes not getting loadedspl_autoload_reqister 类未加载
【发布时间】:2014-03-07 21:29:03
【问题描述】:

我的文件夹结构看起来像

base_dir-
        Includes.php
        Libs-
             Database.php
             Log.php
             Cofing.php
        Models-
             someClass.php
        Scheduled-
             test.php

我的Includes.php

spl_autoload_register(NULL, FALSE);

spl_autoload_extensions('.php, .class.php, lib.php');

function libLoader($name) {
    $file = 'Libs/' . $name . '.php';
    if (!file_exists($file)) {
        // throw new Exception("Error Loading Library: $file does not exists!", 1);
        return FALSE;
    }
    require_once $file;
}

function modelLoader($name) {
    $file = 'Models/' . $name . '.php';
    if (!file_exists($file)) {
        // throw new Exception("Error Loading Library: $file does not exists!", 1);
        return FALSE;
    }
    require_once $file;
}

spl_autoload_register('libLoader');
spl_autoload_register('modelLoader');

我的someClass.php

require_once '../Includes.php';
class someClass extends Database
{
    public function __construct() { return 'hello world'; }
}

test.php

require_once '../Includes.php';

try {
     $loads = new someClass();
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage();
}

当我运行 test.php 时,我得到 someClass not found on .../Scheduled/test.php

spl 是否适用于像 someClass.php 这样的扩展类,还是我需要包含要扩展的类?

为什么它找不到someClass.php

谢谢

【问题讨论】:

  • 这听起来可能很愚蠢,但如果您使用的是自动加载器,为什么您的someClass.php 中有require_once '../Includes.php';
  • 尝试在您的模型自动加载器中将$file = 'Models/' . $name . '.php'; 更改为$file = __DIR__ . '/Models/' . $name . '.php';,并且您的libLoader 中的等价物也确保它从正确的目录搜索,而不是您的test.php 文件所在的目录
  • @MarkBaker 谢谢这实际上解决了这个问题。你能把它作为一个答案,以便我可以将其标记为已回答

标签: php spl-autoload-register spl-autoloader


【解决方案1】:

改变

$file = 'Models/' . $name . '.php'; 

$file = __DIR__ . '/Models/' . $name . '.php'; 

在您的模型自动加载器(以及您的 libLoader 中的等价物)中,以确保它从正确的目录中搜索,而不是您的 test.php 文件所在的目录

【讨论】:

    猜你喜欢
    • 2011-08-02
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    相关资源
    最近更新 更多