php中__autoload和spl_autoload_register的用法
2015-12-29 15:19
621 查看
__autoload方法是用于类的的自动加载的。如果没有这个方法,在调用各种类的时候则需要引入各种类文件。
比如有一个类文件HelloWord.class.php:
class HelloWord{ public function doPrint(){ echo "helloWord"; } }
如果要调用HelloWord这个类的话则必须引入HelloWord.class.php,如果要调用很多类似的类则需要引入各种文件,整个代码的可读性就会很差,使用__autoload则可以有效解决这个问题
<?php function __autoload($class){ $file = $class.".class.php"; if(is_file($file)){ require($file); } } $class = new HelloWord(); $class->doPrint(); ?>
上述代码很好理解PHP在实例化HelloWord这个类的时候回去先访问__autoload()这个方法并更具方法中的规则引入类文件
spl_autoload_register方法也是实现自动加载类文件的功能,不过他是注册给定的函数作为 __autoload 的实现
上述代码可以改为:
<?php function autoload($class){ $file = $class.".class.php"; if(is_file($file)){ require($file); } } spl_autoload_register("autoload"); $class = new HelloWord(); $class->doPrint();
同样也可以实现自动加载的方法,spl_autoload_register也可以将类中的静态方法作为自动加载方法调用:
spl_autoload_register(array('$className','$function'));
相关文章推荐
- PHP中__autoload()与spl_autoload_register()函数的用法与区别
- PHP中spl_autoload_register()函数用法实例详解
- PHP中spl_autoload_register()函数用法实例详解
- PHP的spl_autoload_register用法
- PHP中spl_autoload_register()函数的用法
- PHP中spl_autoload_register()函数的用法
- 【thinkphp3.x】PHP中spl_autoload_register()函数的用法
- PHP中spl_autoload_register()函数的用法
- PHP spl_autoload_register()函数的一些见解
- PHP函数spl_autoload_register()用法和__autoload()介绍
- PHP中spl_autoload_register函数的用法
- PHP中spl_autoload_register函数的用法
- PHP函数spl_autoload_register()用法和__autoload()介绍
- PHP 自动载入,实例化对象时自动include类文件(spl_autoload_register)
- PHP中spl_autoload_register()和__autoload()区别分析
- PHP函数spl_autoload_register()用法和__autoload()介绍
- PHP中spl_autoload_register函数的用法
- PHP中spl_autoload_register函数的用法
- 自动加载类PHP中spl_autoload_register函数的用法
- PHP 命名空间与自动加载机制介绍,spl_autoload_register, __autoload 函数