autoload函数
(PHP 5, PHP 7)
定义:void __autoload(string $class)
作用:
遇到类使用时,自动尝试加载未定义的类。
使用方法:
自定义自动加载的方法,参数为类名,例如function __autoload($classname) {
$filename=SITE_ROOT.'/model/'.strtolower($classname).'.php';
include_once($filename);
}
注意:在文件作用域内只能有一个__autoload函数。
apl_autoload_register函数
(PHP 5 >= 5.1.2, PHP 7)
定义:bool spl_autoload_register([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]])
参数:
autoload_function:欲注册的自动装载函数。未设置则自动注册 autoload 的默认实现函数spl_autoload()。
throw:此参数设置了 autoload_function 无法成功注册时, spl_autoload_register()是否抛出异常。
prepend:如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部
作用:
注册给定的函数作为__autoload函数执行,可注册多个函数,形成__autoload函数序列,默认失败抛出异常,成功注册则添加函数到队列末尾。
使用方法:
定义一个函数,参数为类名,和__autoload一样,但名字不同,然后调用spl_autoload_register注册即可。
注册类的静态函数时,可以使用两种写法,如Example类下的test函数:// 方法一:数组,第一个值为类名,第二个为函数名
spl_autoload_register(array('Example', 'test'));
// 方法二:使用命名空间法
spl_autoload_register('Example::test');
两种方法作用是一样的。