PHP的autoload自动加载机制使用说明

在PHP开发过程当中,若是但愿从外部引入一个class,一般会使用include和require方法,去把定义这个class的文件bao含进来,可是这样可能会使得在引用文件的新脚本中,存在大量的include或require方法调用,若是一时疏忽遗漏则会产生错误,使得代码难以维护。 自PHP5后,引入了__autoload这个拦截器方法,能够自动对class文件进行bao含引用,一般咱们会这么写:
php

function __autoload($className) { 
    include_once $className . '.class.php'; 
} 
$user = new User();

当PHP引擎试图实例化一个未知类的操做时,会调用__autoload()方法,在PHP出错失败前有了最后一个机会加载所需的类。所以,上面的这段代码执行时,PHP引擎实际上替咱们自动执行了一次__autoload方法,将User.class.php这个文件bao含进来。 在__autoload函数中抛出的异常不能被catch语句块捕获并致使致命错误。 若是使用 PHP的CLI交互模式时,自动加载机制将不会执行。 当你但愿使用PEAR风格的命名规则,例如须要引入User/Register.php文件,也能够这么实现: 安全

//加载我 
function __autoload($className) { 
    $file = str_replace('_', DIRECTORY_SEPARATOR, $className); 
    include_once $file . 'php'; 
} 
$userRegister = new User_Register();

这种方法虽然方便,可是在一个大型应用中若是引入多个类库的时候,可能会由于不一样类库的autoload机制而产生一些莫名其妙的问题。在PHP5引入SPL标准库后,咱们又多了一种新的解决方案,spl_autoload_register()函数。 此 函数的功能就是把函数注册至SPL的__autoload函数栈中,并移除系统默认的__autoload()函数。一旦调用 spl_autoload_register()函数,当调用未定义类时,系统会按顺序调用注册到spl_autoload_register()函数的全部函数,而不是自动调用__autoload()函数,下例调用的是User/Register.php而不是 User_Register.class.php:
函数

//不加载我 
function __autoload($className) { 
    include_once $className . '.class.php'; 
} 
//加载我 
function autoload($className) { 
    $file = str_replace('/', DIRECTORY_SEPARATOR, $className); 
    include_once $file . '.php'; 
} 
//开始加载 
spl_autoload_register('autoload'); 
$userRegister = new User_Register();

在使用spl_autoload_register()的时候,咱们还能够考虑采用一种更安全的初始化调用方法,参考以下:
ui

//系统默认__autoload函数 
function __autoload($className) { 
    include_once $className . '.class.php'; 
} 
//可供SPL加载的__autoload函数 
function autoload($className) { 
    $file = str_replace('_', DIRECTORY_SEPARATOR, $className); 
    include_once $file . '.php'; 
} 
//不当心加载错了函数名,同时又把默认__autoload机制给取消了……囧 
spl_autoload_register('_autoload', false); 
//容错机制 
if(false === spl_autoload_functions()) { 
    if(function_exists('__autoload')) { 
        spl_autoload_register('__autoload', false); 
   } 
}