spl_autoload_register()函数
2016-01-18 15:17
169 查看
一、__autoload
这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。看下面例子:
运行index.php后正常输出hello world。在index.php中,由于没有包含printit.class.php,在实例化printit时,自动调用__autoload函数,参数$class的值即为类名printit,此时printit.class.php就被引进来了。
在面向对象中这种方法经常使用,可以避免书写过多的引用文件,同时也使整个系统更加灵活。
二、spl_autoload_register()
再看spl_autoload_register(),这个函数与__autoload有与曲同工之妙,看个简单的例子:
将__autoload换成loadprint函数。但是loadprint不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。
spl_autoload_register() 调用静态方法
转自:http://blog.csdn.net/panpan639944806/article/details/23192267
这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。看下面例子:
printit.class.php <?php class PRINTIT { function doPrint() { echo 'hello world'; } } ?> index.php <? function __autoload( $class ) { $file = $class . '.class.php'; if ( is_file($file) ) { require_once($file); } } $obj = new PRINTIT(); $obj->doPrint(); ?>
运行index.php后正常输出hello world。在index.php中,由于没有包含printit.class.php,在实例化printit时,自动调用__autoload函数,参数$class的值即为类名printit,此时printit.class.php就被引进来了。
在面向对象中这种方法经常使用,可以避免书写过多的引用文件,同时也使整个系统更加灵活。
二、spl_autoload_register()
再看spl_autoload_register(),这个函数与__autoload有与曲同工之妙,看个简单的例子:
<? function loadprint( $class ) { $file = $class . '.class.php'; if (is_file($file)) { require_once($file); } } spl_autoload_register( 'loadprint' ); $obj = new PRINTIT(); $obj->doPrint(); ?>
将__autoload换成loadprint函数。但是loadprint不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。
spl_autoload_register() 调用静态方法
<? class test { public static function loadprint( $class ) { $file = $class . '.class.php'; if (is_file($file)) { require_once($file); } } } spl_autoload_register( array('test','loadprint') ); //另一种写法:spl_autoload_register( "test::loadprint" ); $obj = new PRINTIT(); $obj->doPrint(); ?>
转自:http://blog.csdn.net/panpan639944806/article/details/23192267
相关文章推荐
- [ActionScript 3.0] AS3.0 调试出现安全沙箱冲突错误解决办法
- php接收表单中有大数组存在时的问题
- ambari部分rest api
- 用ListView和GridView实现的,第一个item默认选中的二级列表
- 树形结构的处理——组合模式(二):组合模式概述
- 最简单的提升网页加载速度的三种方式
- Java运用SWT插件编写桌面记事本应用程序
- Android View的绘制流程
- python2.7.6 pip install 报错
- php in_array的性能问题,附加调试方法
- iOS 多语言版本的开发
- 释放虚拟磁盘未使用空间来减少计费容量
- 释放虚拟磁盘未使用空间来减少计费容量
- 释放虚拟磁盘未使用空间来减少计费容量
- android:json解析的两个工具:Gson和Jackson的使用小例子
- 如何处理iOS中照片的方向
- Android四大组件之Activity--Activity生命周期(一)
- 释放虚拟磁盘未使用空间来减少计费容量
- JSP自定义标签由浅到深详细讲解(全)
- IEEE Std 802.11TM-2012 WLAN MAC and PHY specifications-第7章 物理层规格03