“spl_autoload_extension()”与“spl_aautoload_register()”的用法是什么


what is the usage of `spl_autoload_extension() `with `spl_autoload_register()`?

我正在使用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();没有影响。为什么?

我也读过这个博客,但不知道如何实现。

这样做没有错。两种不同的类文件自动加载器是可以的,但我会给它们多一点描述性的名称;)

注:对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';
    }
});

也许这会有所帮助:

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

Jeremy Cook 2010年9月3日06:46

任何使用此功能添加自己的自动加载的人的快速提示扩展。我发现,如果我在不同的扩展(即".php,.class.php"),函数不会工作为了让它发挥作用,我不得不去掉扩展(即".php,.class.php")。这在php 5.3.3上进行了测试Windows和我正在使用spl_autoload_register(),而不添加任何自定义自动加载功能。

希望这能帮助到别人。