PHP自动加载函数

来源:互联网 发布:淘宝pc客户端官方下载 编辑:程序博客网 时间:2024/05/12 06:41

__autoload() :PHP原生的函数

spl_autoload():PHP的C扩展函数

两者的速度,区别很明显了。

自动加载俗称:Lazy Loading

<?php/** * 实现自动加载类 * FAQ:需要引入一个类文件,如show.php,类名为Show,然后使用 $obj = new Show();  * 无须使用"include, include_once, require, require_once",实现自动加载类。 */// By PHP手册// bool spl_autoload_register([callback $autoload_function]) // 可实现自动注册函数和类,实现类似__autoload() 函数功能,简化了类的调用与加载//第一种方式:函数式function my_autoload ($className) {include(__DIR__ . DIRECTORY_SEPARATOR . $className . ".php");}spl_autoload_register('my_autoload');//第二种方式:类式class autoload{public function load($className){include(__DIR__ . DIRECTORY_SEPARATOR . $className . ".php");}}spl_autoload_register(array('load', 'autoload'));spl_autoload_register('autoload::load');// 将函数注册到SPL __autoload函数栈中。如果该栈中的函数尚未激活,则激活它们。// 如果在你的程序中已经实现了__autoload函数,它必须显式注册到__autoload栈中。// 因为 spl_autoload_register()函数会将Zend Engine中的__autoload函数取代为spl_autoload()或spl_autoload_call()。// __autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法// 可以通过下面的方法来把 _autoload 方法加入 autoload_functions listspl_autoload_register('__autoload');// autoload机制的主要执行过程为:// (1) 检查执行器全局变量函数指针autoload_func是否为NULL。// (2) 如果autoload_func==NULL, 则查找系统中是否定义有__autoload()函数,如果没有,则报告错误并退出。// (3) 如果定义了__autoload()函数,则执行__autoload()尝试加载类,并返回加载结果。// (4) 如果autoload_func不为NULL,则直接执行autoload_func指针指向的函数用来加载类。注意此时并不检查__autoload()函数是否定义。// SPL autoload机制的实现是通过将函数指针autoload_func指向自己实现的具有自动装载功能的函数来实现的。// SPL有两个不同的函数 spl_autoload, spl_autoload_call,通过将autoload_func指向这两个不同的函数地址来实现不同的自动加载机制。// 怎样让spl_autoload自动起作用呢,也就是将autoload_func指向spl_autoload?// 答案是使用 spl_autoload_register函数。在PHP脚本中第一次调用spl_autoload_register()时不使用任何参数,就可以将 autoload_func指向spl_autoload。