微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

详解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"  ); 
?>





版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐