PHP spl_autoload_register

Jon*_*noB 30 php spl-autoload-register

我试图利用PHP中的自动加载.我在不同的目录中有各种类,所以我已经引导自动加载如下:

function autoload_services($class_name)
{
    $file = 'services/' . $class_name. '.php';
    if (file_exists($file))
    {
        require_once($file);
    }
}

function autoload_vos($class_name)
{
    $file = 'vos/' . $class_name. '.php';
    if (file_exists($file))
    {
        require_once($file);
    }
}

function autoload_printers($class_name)
{
    $file = 'printers' . $class_name. '.php';
    if (file_exists($file))
    {
        require_once($file);
    }
}

spl_autoload_register('autoload_services');
spl_autoload_register('autoload_vos');
spl_autoload_register('autoload_printers');
Run Code Online (Sandbox Code Playgroud)

这一切似乎都很好,但我只想仔细检查这确实被认为是可以接受的做法.

mr.*_*. w 32

当然,看起来不错.你可能做的唯一事情是按照他们最有可能命中的顺序注册它们.例如,如果您最常用的类是服务,然后是vos,然后是打印机,那么您的订单就是完美的.这是因为它们按顺序排队并调用,因此通过执行此操作可以获得稍微更好的性能.

  • 另外..没有必要使用include/require_once.当系统无法找到您要实例化的类时,Autoload是一个后备.如果您已经通过自动加载将其包含一次,那么系统会知道它并且无论如何都不会再次运行自动加载方法.所以,只需使用常规include/require - 它们更快. (17认同)

Nik*_*kiC 19

You could use:

set_include_path(implode(PATH_SEPARATOR, array(get_include_path(), './services', './vos', './printers')));
spl_autoload_register();
Run Code Online (Sandbox Code Playgroud)

Using spl_autoload_register without arguments will register spl_autoload which will look for the class name in the directories of the include path. Note that this will lowercase the class name before looking for it on the filesystem.

  • >小写类名--- Gah!为什么?这意味着在Windows上运行的代码可能不在*nix系统上. (9认同)