spl_autoload_register() && __autoload函数
2024-10-18 20:21:13
一、__autoload
这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。
在index.php中,由于没有包含test.class.php,在实例化printit时,自动调用__autoload函数,参数$class的值即为类名printit,此时test.class.php就被包含进来了。
eg:
test.class.php <?php class test { function doPrint() {
echo 'hello world';
}
}
?> index.php <?
function __autoload( $class ) {
$file = $class . '.class.php';
if ( is_file($file) ) {
require_once($file);
}
} $obj = new test();
$obj->doPrint();
?>
二、spl_autoload_register()
spl_autoload_register(),这个函数与__autoload有与曲同工之妙,将__autoload换成自定义函数。但是该自定义函数不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行该自定义函数()。
<? class test {
public static function myAuto( $class ) {
$file = $class . '.class.php';
if (is_file($file)) {
require_once($file);
}
}
} class myTest {
function doPrint() {
echo 'hello world';
}
} spl_autoload_register( array('test',myAuto) ); //另一种写法:spl_autoload_register( "test::myAuto" ); $obj = new myTest ();
$obj->doPrint();
?>
最新文章
- spring-boot 和 docker 集成
- [原创]首次制作JQueryUI插件-Timeline时间轴
- [转]C#如何把文件夹压缩打包然后下载
- Hibernate saveOrUpdate方法到底是怎么执行的?
- Oracle权限和数据类型
- SQL2012新特性一次一个数据块----特殊的查询分页
- 转:Eclipse常用开发插件
- php curl post
- poj3321Apple Tree(树状数组)
- PHP开发APP接口(二)
- 初始Android-配置环境
- 初入ubuntu
- bzoj 4310: 跳蚤
- LOJ116 - 有源汇有上下界最大流
- 3. [leetcode] Longest Substring Without Repeating Characters
- letCode-1
- Django之Django终端打印SQL语句
- 【hexo】02完成本地创建
- vue 关于npm run build 的小问题
- 背水一战 Windows 10 (42) - 控件(导航类): Frame 动画
热门文章
- Google Colab调用cv2.imshow奔溃
- maven项目在myeclipse中不出现Maven Dependencies 和maven标识的解决方法
- 【Qt】2.2 继续了解信号和槽
- Window命令行杀进程
- 学习笔记之30个常用的maven命令
- Fortran学习笔记6(函数、子程序)
- [LUOGU] P2543 [AHOI2004]奇怪的字符串
- js获取移动端触摸坐标
- verilog behavioral modeling--sequential and parallel statements
- 学习Gulp过程中遇到的一些单词含义