zoukankan      html  css  js  c++  java
  • 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' );

    即可。

  • 相关阅读:
    adb
    js百分比
    隐私策略
    JSON.parse&JSON.stringify
    MVC内容backgroundimage: url('')问题
    mvc笔记
    winform路径
    配置
    邮件发送的原理
    如何调试Windows服务
  • 原文地址:https://www.cnblogs.com/zox2011/p/2760351.html
Copyright © 2011-2022 走看看