spl_autoload_register 函数的功能就是把传入的函数(参数可以为回调函数或函数名称形式)注册到 SPL autoload 函数队列中,并移除系统默认的 autoload() 函数。
一旦调用 spl_autoload_register() 函数,当调用未定义类时,系统就会按顺序调用注册到 spl_autoload_register() 函数的所有函数,而不是自动调用 __autoload() 函数。
autoload() 函数作用,当使用一个未引入的类时,会执行此函数,此函数有个参数即要使用的类名,如下
当实例化Abc时,就会自动执行autoload方法
function __autoload($classname){
echo '我被调用了';
$classpath = './' . $classname . '.php';
if (file_exists($classpath)){
require_once($classpath);
}else{
echo $classpath . ' not be found';
}
}
$instance = new Abc();
自php5.1之后,可以使用spl_autoload_register() 函数自定义自动加载函数
1、调用函数
function myLoad($classname){
$classpath = './' . $classname . '.php';
if (file_exists($classpath)){
require_once($classpath);
}else{
echo $classpath . ' not be found';
}
}
spl_autoload_register('myLoad');
2、调用类中静态方法
class Test{
static function myLoad($classname){
$classpath = './' . $classname . '.php';
if (file_exists($classpath)){
require_once($classpath);
}else{
echo $classpath . ' not be found';
}
}
}
spl_autoload_register(['test','myLoad']);//1
spl_autoload_register( "test::myLoad" );//2
此外,还有几点
spl_autoload_register可多次调用,注册的多个函数将在事件发生时依次执行。
bool spl_autoload_register([ callable throw = true [, bool $prepend = false ]]])
autoload_function欲注册的自动装载函数。如果没有提供任何参数,则自动注册 autoload 的默认实现函数spl_autoload()。
throw此参数设置了 autoload_function 无法成功注册时, spl_autoload_register()是否抛出异常。
prepend如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。