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()返回所有已经注册的函数等。

      

      

  • 相关阅读:
    BZOJ 1630/2023 Ant Counting 数蚂蚁
    BZOJ 3997 组合数学
    BZOJ 2200 道路与航线
    BZOJ 3181 BROJ
    BZOJ 4011 落忆枫音
    BZOJ 4027 兔子与樱花
    vijos 1741 观光公交
    vijos 1776 关押罪犯
    vijos 1780 开车旅行
    5、异步通知机制
  • 原文地址:https://www.cnblogs.com/flzs/p/14273351.html
Copyright © 2011-2022 走看看