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' );

即可。

转载于:https://www.cnblogs.com/zox2011/archive/2012/11/08/2760351.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值