php 自动加载类函数spl_autoload_register()
2016-02-18 09:45
591 查看
php手册已经建议使用该函数spl_autoload_register(),而不再建议使用魔术方法__autoload(),这里也只做spl_autoload_register()解释。文档中描述的是spl_autoload_register()可以进行多个解释,而__atuoload()只是一个。
If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.
spl_autoload_register 可以很好地处理需要多个加载器的情况,这种情况下 spl_autoload_register 会按顺序依次调用之前注册过的加载器。作为对比, __autoload 因为是一个函数,所以只能被定义一次。
spl_autoload_register()函数可以直接加载一个自定义函数用于引入类文件进行类查找,也可以以数组的形式加载一个类里面的静态加载类文件方法。
If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.
spl_autoload_register 可以很好地处理需要多个加载器的情况,这种情况下 spl_autoload_register 会按顺序依次调用之前注册过的加载器。作为对比, __autoload 因为是一个函数,所以只能被定义一次。
spl_autoload_register()函数可以直接加载一个自定义函数用于引入类文件进行类查找,也可以以数组的形式加载一个类里面的静态加载类文件方法。
加载自定义类的静态方法
class LOAD { //必须传入类名,与文件名/类名称一致 static function loadclass($class) { // 该处可以自定义加载的路径 $file = $class.'.class.php'; if (is_file($file)) { require_once($file); } } } /* 未找到未定义类时调用 */ spl_autoload_register(array('LOAD', 'loadclass')); //例子 $view = new Test; //当初始化时会自动去寻找文件里面的Test echo $view::test1();
直接加载
function load_class($class) { $file = $class.'.class.php'; if (is_file($file)) { require_once($file); } } /* 未找到未定义类时调用 */ spl_autoload_register('load_class'); $view = new Test; echo $view::test1();
另外,给出另一个类文件Test.class.php
<?php class Test { public static function test1() { echo 1; } }
相关文章推荐
- PHP和MySql中32位和64位的整形范围是多少
- 我做的一个websocket的demo(php server)
- php简易计算器
- ThinkPHP无限级分类
- php正则表达式及字符串处理函数
- vsftpd 本地用户无法登陆 530 Login incorrect
- PHP——0127加登录页面,加查询,加方法,加提示框
- PHP和MySql中32位和64位的整形范围是多少
- php实现中文转数字
- php强大的时间转换函数strtotime
- php 生成二维码
- php screw加密
- PHP如何实现异步数据调用
- PHP如何获取客户端真实IP
- github上比较有趣的php项目
- phpmailer用法
- PayPal Express Checkout with PHP-code
- php保留关键字
- ubuntu安装PHP的swoole扩展
- PHP的静态变量