自動載入主要是省去了一個個類去 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__, "()\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"; } } ?>
實驗結果:
$ 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 已經做了緩存,所以,這種方式應該是拿內存換了速度。