【问题标题】:Using spl_autoload() not able to load class使用 spl_autoload() 无法加载类
【发布时间】:2011-03-12 08:38:07
【问题描述】:

我正在使用 SPL 自动加载功能,但似乎遗漏了一些重要的东西,因为我目前无法让它工作。这是我目前使用的 sn-p:

// ROOT_DIRECTORY translates to /home/someuser/public_html/subdomains/test
define('ROOT_DIRECTORY', realpath(dirname(__FILE__)));
define('INCLUDE_DIRECTORY', ROOT_DIRECTORY . '/includes/classes/');
set_include_path(get_include_path() . PATH_SEPARATOR . INCLUDE_DIRECTORY);
spl_autoload_extensions('.class.php, .interface.php, .abstract.php');
spl_autoload_register();

当我echo get_include_path() 时,我确实得到了我期望的路径:

// Output echo get_include_path();
.:/usr/lib/php:/usr/local/lib/php:/home/someuser/public_html/subdomains/test/includes/classes/

但是,当我运行代码时,我收到以下错误消息:

致命错误:spl_autoload() [function.spl-autoload]: Class Request 无法加载 /home/someuser/public_html/subdomains/test/contact.php 在第 5 行

Request.class.php肯定在 /home/someuser/public_html/subdomains/test/includes/classes/ 目录中。

我错过了什么?

【问题讨论】:

  • @Yannis Rizos - 这确实是我的问题。将此作为答案,以便我投票并为您提供正确答案。

标签: php spl spl-autoloader


【解决方案1】:

我收到了类似的错误消息,但我的问题有所不同。我的错误信息看起来像

PHP Fatal error:  spl_autoload(): Class Lib\Lib\Regex could not be loaded in /dir1/dir2/lib/regex.php on line 49

原来我忘了从 Regex 类定义本身的 Lib\Regex 中删除 Lib\。我有类似以下内容:

namespace Lib;

class Regex {

...

   public static function match($pattern, $str) {

      $regex = new Lib\Regex($pattern);

      ...
   }
}

【讨论】:

    【解决方案2】:

    http://www.php.net/manual/en/function.spl-autoload-register.php#96804 上有一条评论(匿名)可能适用于您的问题:spl_autoload_register() 似乎不适合使用驼峰式,在您的情况下可能会尝试查找 request.class.php 而不是请求...

    【讨论】:

    • 我也发现了这个错误。一旦我将类名更改为小写,一切正常。您知道这是否已被报告为错误?
    • 这里有一些漏洞。可笑的是,这仍然是一个问题。我浏览了错误系统并对相关问题进行了投票,这是一个很好的起点:bugs.php.net/bug.php?id=53065.
    • 如果你仍然想使用 spl,你可以使用一个重载默认函数的闭包,这样你就不会被小写:spl_autoload_register( function( $class ) { include $class . '.php'; }); - 调整你的路径;)
    • 不一定是大交易,但不使用默认的 spl_autoload() 并定义您自己的会由于在包含函数期间生成的 stat() 执行而产生性能损失...在 cmets 上看到它php 文档...
    【解决方案3】:

    该类的路径似乎与您期望的路径不匹配。比较

    .:/usr/lib/php:/usr/local/lib/php:/home/someuser/public_html/subdomains/test/includes/classes/
    

    /home/someuser/public_html/subdomains/test/
    

    不同之处在于,您的班级不在includes/classes/ 中,因为您的 SPL 需要它,而是在上面的几个目录中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 2017-11-27
      • 2021-06-21
      • 2021-12-02
      相关资源
      最近更新 更多