__autoload()函数可以实现自动加载所需要的类
用法:
__autoload() 在实例化对象时,若没有引入相关的文件,就会自动调用这个方法来进行加载。
实例:
public function __autoload($className)
{
$actionPath ="E://project/LiB/Action/".$className.".class.php";
if(!file_exists($actionPath))
{
echo $actionPath."路径不存在";
}
require_once($actionPath);
}
spl_autoload_register()函数
作用:注册自定义加载函数
比如在文件中定义一个 loadfile()作为自定义加载函数,但是至少声明或者定义这个函数后,在实例化对象时,程序并不会自动去运行loadfile()这个函数,而会自动运行__autoload()函数。而spl_autoload_register()函数就是让程序在实例化一个对象时组自动调用loadfile()函数。
实例:
class test
{
public function testLoad()
{
echo "这是test类中的testLoad方法";
}
}
?>
spl_autoload_register(array("AutoLoad", "autoLoadCore"), '', true); //注册自动加载方法
//定义自定义加载函数
public static function autoLoadCore($classname)
{
$classPath = "E://project/LiB/Action/".$className.".class.php";
if(!file_exists($classPath))
{
echo $classPath."路径不存在";
}
require_once($classPath);
}
$test = new test();
$test->testLoad();
?>
结果: 输出:这是test类中的testLoad方法;
spl_autoload_register()有三个参数
第一个:array($classname,$method),是一个数组,数组有两个元素,第一个元素表示自动加载方法所在的类,第二个表示自动加载方法的函数名
第二个参数:表示无法成功注册时是否抛出异常,true/false
第三个参数:true/false,表示是否将函数注册到自动加载函数队列之首。
注意:1、spl_autoload_register()实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行(至今我没有成功实现逐个执行的功能,请各位指点)
2、若使用spl_autoload_register()注册了新的自动加载函数,那么原有的__autoload()函数将失效,若需使用__autoload()函数,需要通过spl_autoload_register()再次注册__autoload()函数,方能在使用此函数