zoukankan      html  css  js  c++  java
  • spl_autoload_register()和__autoload()区别

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

    <?php
    class PRINTIT {
     function doPrint() {
     echo 'hello world';
     }
    }
    ?>
    

      

    <?
    function __autoload( $class ) { $file = $class . '.class.php'; if ( is_file($file) ) { require_once($file); } } $obj = new PRINTIT(); $obj->doPrint();?>

    运行index.php后正常输出hello world

    二、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();?>
    

    使用spl_autoload_register()的好处是不可言喻的:
    (1)自动加载对象更加方便,很多框架都是这样做的

    (2)你要知道__autoload()函数只能存在一次啊,spl_autoload_register()当然能注册多个函数

    (3)SPL函数很丰富,提供了更多功能,如spl_autoload_unregister()注销已经注册的函数、spl_autoload_functions()返回所有已经注册的函数等。

      

      

  • 相关阅读:
    理解缓慢变化维(Slowly Changing Dimension)
    分析Reporting Service的报表执行记录
    XCOPY
    Esxi主机从VC断开的怪事
    奇怪的SQLserver执行
    明细表达到15亿了
    现在才知道“quota”
    oledb读取Excel数据丢失原因
    配置subversion
    sql服务器的操作系统升级,数据库如何来迁移呢?
  • 原文地址:https://www.cnblogs.com/flzs/p/14273351.html
Copyright © 2011-2022 走看看