zoukankan      html  css  js  c++  java
  • php自动加载函数

    含义:将函数注册到SPL __autoload函数栈中。如果该栈中的函数尚未激活,则激活它们。
    先看__autoload 函数

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

    在index.php中,由于没有包含printit.class.php,在实例化printit时,自动调用__autoload函数,参数$class的值即为类名printit,此时printit.class.php就被引进来了。

    <?
    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()。

    调用静态方法

    <?
    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();
    ?>
  • 相关阅读:
    greenplum 常用整理
    postgresql 常用整理
    数据源整理
    hive 以like方式建表(携带表结构)
    kudu 常用整理
    mysql常用整理
    Linux查看文件内容的常用方式(more,less,head,tail,cat)
    python2.7 安装docx错误
    python2.7 安装搜索引擎错误
    mysql数据库安装错误
  • 原文地址:https://www.cnblogs.com/wanghaokun/p/6104188.html
Copyright © 2011-2022 走看看