PHP 類的命名空間 和自動載入


PHP 類的自動載入有兩種方法,__autoload() 和 spl_autoload_register() ,就是在PHP代碼中new一個類的時候,會自動觸發,將類的類名包括命名空間作為參數傳進入方法里,在方法里可根據命名空間和類名准確找到類文件,從而require或者inlcude進來。菜鳥一枚,作為備忘

<?php
function auto($class){
        //$class = A\B\E;
        /** 命名空間的自動載入 **/
        $class_path = explode("\\",$class);
        $file = __DIR__ . '/' ;
        foreach($class_path as $c){
           $file .= $c . '/';
        }
        $file = rtrim($file,"/");
        $file .= '.php';
        var_dump($file);exit;
}
spl_autoload_register('auto');
use A\B\E;
$e = new E();
echo 'hi';
/*******輸出*******/
string(32) "/www/test_php_autoload/A/B/E.php"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM