zoukankan      html  css  js  c++  java
  • PHP 实现自动加载

    自动载入主要是省去了一个个类去 include 的繁琐,在 new 时动态的去检查并 include 相应的 class 文件。

    先上代码:

    //index.php
    <?php
    
    class ClassAutoloader {
        public static function loader($className)
        {
            $file = $className . ".class.php";
            
            if(is_file($file))
            {
                echo 'Trying to load ', $className, ' via ', __METHOD__, "()
    ";
                require_once( $file );
            }
            else
            {
                echo 'File ', $file, " is not found!
    ";
            }
        }
    
        public static function register($autoLoader = '')
        {
            spl_autoload_register($autoLoader ?: array('ClassAutoloader', 'loader'), true, true);
        }
    }
    
    ClassAutoloader::register();
    
    $obj = new printit();
    $obj->doPrint();
    
    ?>

    然后是类文件:

    //printit.class.php 
    <?php 
    
    class PRINTIT { 
    
     function doPrint() {
      echo "Hello, it's PRINTIT! 
    ";
     }
    }
    ?> 

    实验结果:

    $ php index.php 
    Try to load printit via ClassAutoloader::loader()
     
    Hello, it's PRINTIT! 

    上面的代码中,我们在另外一个文件 printit.class.php 中定义的 printit 类。但是,我们并没有在 index.php 中显性的 include 这个库文件。然后,因为我们有注册了自动加载方法,所以,我们在 new 这个类时,我们的自动加载方法就会按事先定义好的规则去找到类文件,并 include 这个文件。

    这也是 ThinkPHP5.1 中 Loader 的基本原理。不过,ThinkPHP 框架中,另外还增加了使用 Psr0、Psr4 规则来查找类文件,以及 Composer 的自动加载。

    PS,在官方文档的评论中,看到这样的神级代码:

    <?php
        spl_autoload_extensions(".php"); // comma-separated list
        spl_autoload_register();
    ?>

    让 PHP 自己去寻找文件,据说要比上面指定文件名要快得多。

    该评论中举例,1000 classes (10个文件夹,每个有 10个子文件夹,每个文件夹有 10 个类)时候,上面指定文件名的方式耗时 50ms,而这两句代码只花了 10ms。

    不过我猜,第一句让 PHP 已经做了缓存,所以,这种方式应该是拿内存换了速度。

  • 相关阅读:
    Codeforces Round #171 (Div. 2)
    ACdream 1079 郭式树
    HDOJ 1517 博弈论
    ACdream 1080 面面数
    博弈论 Nim 博弈
    Codeforces Round #172 (Div. 2)
    ACdream 1084 同心树
    STL bitset
    博弈论 bash博弈
    POJ 3261 后缀数组
  • 原文地址:https://www.cnblogs.com/pied/p/10309300.html
Copyright © 2011-2022 走看看