php中的自动加载

第一种方法是 __autoload();

在找不到类的时候自动调用这个方法

<?php
     define('DIR',dirname(__FILE__).'/');
     function __autoload($classname){
          $filename = DIR.$classname.'.class.php';
          if(file_exists($filename)){
               include_once $filename;
          }else{
               echo "  no class file !";
          }
     }
?>                

 但是一个项目或者是框架中如果,需要不通的加载机制,那么都写在一个__autoload中就使它变得非常的臃肿。不方便维护和管理。

 为了进一步的维护和管理自动加载我们可以用第二种方法

 第二种方法 spl_autoload_register();

 

<?php
     define('DIR',dirname(__FILE__).'/');
     function autoload1($classname){
          $filename = DIR.$classname.'.class.php';
          if(file_exists($filename)){
               include_once $filename;
          }else{
               echo "  no class file !";
          }
     }
     spl_autoload_register('autoload1');
?> 

 如果是类的形式则写成

<?php
     class test(
         public static function autoload1($classname){
             $filename = DIR.$classname.'.class.php';
             if(file_exists($filename)){
                 include_once $filename;
             }else{
                 echo "  no class file !";
             }
         }
    )
    spl_autoload_register(array('test','autoload1'));
?>

这里的方法必须是静态的;


值得注意的是 __autoload 方法在 spl_autoload_register 后会失效,如需使用__autoload()

spl_autoload_register( '__autoload' );

即可。

posted @ 2012-11-08 14:30  Zox  阅读(508)  评论(0编辑  收藏  举报