1

我正在使用spl_autoload_register()函数来包含所有文件。我希望任何具有扩展名.class.php.php将直接包含的类。我做了下面的课程并注册了两个不同的功能,一切正常,但是

我认为有一些方法可以让我只需要注册一个函数就可以将两个扩展包含在一起。

请查看我的功能并告诉我我缺少什么

我的文件夹结构

project
      -classes
           -alpha.class.php
           -beta.class.php
           -otherclass.php
      -includes
           - autoload.php
      -config.inc.php // define CLASS_DIR and include 'autoload.php'

自动加载.php

var_dump(__DIR__); // 'D:\xampp\htdocs\myproject\includes' 
var_dump(CLASS_DIR); // 'D:/xampp/htdocs/myproject/classes/' 
spl_autoload_register(null, false);
spl_autoload_extensions(".php, .class.php"); // no use for now
/*** class Loader ***/
class AL
{
     public static function autoload($class)
     {
          $filename = strtolower($class) . '.php';
          $filepath = CLASS_DIR.$filename;
          if(is_readable($filepath)){
              include_once $filepath;
          }
//          else {
//                trigger_error("The class file was not found!", E_USER_ERROR);
//            }
    }

    public static function classLoader($class)
    {
        $filename = strtolower($class) . '.class.php';
        $filepath = CLASS_DIR . $filename;
        if(is_readable($filepath)){
              include_once $filepath;
          }
    }

}
spl_autoload_register('AL::autoload');
spl_autoload_register('AL::classLoader');

注意:对线没有影响spl_autoload_extensions();。为什么?

我也读了这个博客,但不明白如何实现。

4

2 回答 2

3

你这样做的方式没有任何问题。两种类文件的两个不同的自动加载器很好,但我会给它们稍微描述性的名称;)

注意:对线没有影响spl_autoload_extensions();。为什么?

这只会影响内置的自动加载spl_autoload()

毕竟使用单个加载器可能更容易

 public static function autoload($class)
 {
      if (is_readable(CLASS_DIR.strtolower($class) . '.php')) {
          include_once CLASS_DIR.strtolower($class) . '.php';
      }  else if (is_readable(CLASS_DIR.strtolower($class) . '.class.php')) {
          include_once CLASS_DIR.strtolower($class) . '.class.php';
      }
}

你也可以省略整个班级

spl_autoload_register(function($class) {
    if (is_readable(CLASS_DIR.strtolower($class) . '.php')) {
        include_once CLASS_DIR.strtolower($class) . '.php';
    }  else if (is_readable(CLASS_DIR.strtolower($class) . '.class.php')) {
        include_once CLASS_DIR.strtolower($class) . '.class.php';
    }
});
于 2012-07-26T07:13:23.043 回答
1

也许这会有所帮助:

http://php.net/manual/de/function.spl-autoload-extensions.php

杰里米库克 03-Sep-2010 06:46

任何使用此功能添加自己的自动加载扩展的人的快速说明。我发现如果我在不同的扩展名(即'.php,.class.php')之间包含一个空格,该函数将不起作用。为了让它工作,我必须删除扩展名之间的空格(即'.php,.class.php')。这在 Windows 上的 PHP 5.3.3 中进行了测试,我正在使用 spl_autoload_register() 而不添加任何自定义自动加载函数。

希望对某人有所帮助。

于 2012-07-26T07:07:23.907 回答