zoukankan      html  css  js  c++  java
  • spl_autoload_register() && __autoload函数

    一、__autoload  

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

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

    eg:

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

    二、spl_autoload_register()  

    spl_autoload_register(),这个函数与__autoload有与曲同工之妙,将__autoload换成自定义函数。但是该自定义函数不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行该自定义函数()。 

    <? 
     
    class test {
     public static function myAuto( $class ) {
      $file = $class . '.class.php';  
      if (is_file($file)) {  
       require_once($file);  
      } 
     }
    } 
    
    class myTest {
      function doPrint() {  
      echo 'hello world';
       }
    } 
     
    
     
    spl_autoload_register(  array('test',myAuto)  );
    
    //另一种写法:spl_autoload_register(  "test::myAuto"  ); 
     
    $obj = new  myTest ();
    $obj->doPrint();
    ?>
    
     
  • 相关阅读:
    电脑开机慢是查看与解决方案
    做男人真难
    强大的数据恢复软件--EasyRecovery专业版
    30招让你从头到脚都健康
    教您如何使用SQL中的SELECT LIKE like语句
    SQL server经典电子书、工具和视频教程汇总
    数据开发-经典
    C# 数据操作工具类
    关于web请求中 获取真实IP
    生成二维码
  • 原文地址:https://www.cnblogs.com/jamesbd/p/3995343.html
Copyright © 2011-2022 走看看