spl_autoload_register()自動載入+名稱空間的使用
阿新 • • 發佈:2019-02-10
我們首先在AutoLoading資料夾下建立了一個loading類,舉例來看:AutoLoading\loading:
<?php namespace AutoLoading; class loading { public static function autoload($className) { //把 \ 轉換成(目錄風格符)DIRECTORY_SEPARATOR //便於相容在Linux系統下檔案找,在Windows系統下(/ \ 是通用的); //由於namespace 很規格,所以很快就能直接找到 $fileName = str_replace('\\',DIRECTORY_SEPARATOR, DIR .'\\'.$className).'.php';//替換符號 echo $fileName; if (is_file($fileName)){//判斷檔案是否存在 include ($fileName); } else { echo $fileName.'is not exist'; } } }
上面就是自動載入的引入類檔案的方法,下面使用spl_autoload_register()這個函式來註冊:
index.php
//把當前目錄定義為絕對路徑 define('DIR',dirname(__FILE__這樣便可以很輕鬆的將不同資料夾的的類引如進來。)); //載入類檔案 require DIR . '/loading.class.php'; //必須是static方法呼叫,不能使用use spl_autoload_register("\\AutoLoading\\loading::autoload"); Lib\Db::demo();//引入Lib目錄下的Db類