PHP自動加載機制

一、require / include
最初的文件加載機制是require/include把一個文件加載進來,但是隨着開發規模的增大,複雜性也越來越高,可能造成遺漏或者冗餘,因此在PHP5版本進入自動加載機制(autoload)

require("/var/www/Person.php")
$per = new Person()

//或者
include("/var/www/Person.php")
$per = new Person()

二、PHP 自動加載函數 __autoload()
在new一個class時,PHP系統如果找不到這個類,就會去自動調用本文件中的__autoload($classname)方法,去require對應路徑的類文件,從而實現自動lazy加載,但是現在已經棄用。
首先同目錄新建一個Person類

<?php
class Person {
    public function hello(){
        echo "hello";
    }   
}
<?php

function __autoload($classname) {
    $classpath="./".$classname.'.php';
    if (file_exists($classpath)) {
        require_once($classpath);
    } else {
        echo 'class file'.$classpath.'not found!';
    }   
}

$p = new Person();
$p->hello();

執行時會提示 PHP Deprecated:  __autoload() is deprecated, use spl_autoload_register() instead

三、SPL Autoload Register
可以註冊任意數量的自動加載器,當然也可以單個加載,但是這樣做,對於大型項目來說,極其不方便管理

spl_autoload_register(function($className){
    if (is_file('./' . $className . '.php')) {
        require './' . $className . '.php';
    }                   
});                     

$p = new Person();
$p->hello();

輸出 hello

正確的做法如下:
①定義一個loader加載器

<?php
class Loader {
    public static function autoload($classname) {
        $file = "./".$classname.".php";

        if (file_exists($file)) {
            include $file;
        } else {
            echo 'class file'.$classname.'not found!';
        }   
    }   
}

② 註冊加載器

//引入加載器
include "./Loader.php";

spl_autoload_register("Loader::autoload", true, true);

$p = new Person();
$p->hello();

輸出hello
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章