详解spl_autoload_register()函数
2016-01-28 11:21
501 查看
分类:
php(1)
在了解这个函数之前先来看另一个函数:__autoload。
一、__autoload
这是一个自动加载函数,在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(); |
?> |
在面向对象中这种方法经常使用,可以避免书写过多的引用文件,同时也使整个系统更加灵活。
二、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(); |
?> |
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(); |
?>
相关文章推荐
- ZMQ源码分析(五) --TCP通讯
- Android启动相机拍照并返回图片
- [原创][FPGA]Quartus实用小技巧(长期更新)
- 日志模块logging使用心得
- mac
- Winbond Trusted Platform Module 1.2 驱动安装解决办法详解
- JavaScript统计字符串中每个字符出现次数完整实例
- win8环境python3.5安装lxml
- 从一段代码看fork()函数及其引发的竞争
- 6.1 Controllers -- Introduction
- iOS项目的架构分类
- 前端CSS规范
- CSS中margin-top属性失效问题解决
- JavaScript btoa atob
- 设计模式(二)----- 抽象工厂(AbstractFactory)----(JAVA版)
- 欢迎使用CSDN-markdown编辑器
- 正则表达式在性能测试中的应用(续)
- android图像绘制获取本地图片或拍照图片等图片资源
- SURF算法
- python2.7_1.13_编写一个SNTP客户端