详解PHP spl_autoload_register()函数

在了解这个函数之前先来看另一个函数:__autoload。  

一、__autoload  

这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。看下面例子:  

printit.class.PHP 
 
<?PHP 
class PRINTIT { 
 function doPrint() {
  echo 'hello world';
}
?> 
index.PHP 
<?
__autoload( $class ) {
$file '.class.PHP';  
if is_file($file) ) {  
require_once);  
$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有与曲同工之妙,看个简单的例子:  

  
loadprint( )) {  
spl_autoload_register( 'loadprint' ); 
将__autoload换成loadprint函数。但是loadprint不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。 

spl_autoload_register() 调用静态方法 

<? 
test {
public static    spl_autoload_register(  array'test','loadprint')  );
//另一种写法:spl_autoload_register(  "test::loadprint"  ); 
?>





相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...