PHP 实现自动加载

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

先上代码:缓存

//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__, "()\n";
            require_once( $file );
        }
        else
        {
            echo 'File ', $file, " is not found!\n";
        }
    }

    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! \n";
 }
}
?> 

实验结果:ui

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

上面的代码中,咱们在另一个文件 printit.class.php 中定义的 printit 类。可是,咱们并无在 index.php 中显性的 include 这个库文件。而后,由于咱们有注册了自动加载方法,因此,咱们在 new 这个类时,咱们的自动加载方法就会按事先定义好的规则去找到类文件,并 include 这个文件。spa

 

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

 

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

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

让 PHP 本身去寻找文件,听说要比上面指定文件名要快得多。内存

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

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

相关文章
相关标签/搜索