標籤:include 空間 第三方 技巧 命名
普通的命名空間自動載入後,又對架構不熟,在M層或者C層想include直接調用第三方類時通常都不行會報錯。原因是有命名空間和自動載入這兩個php特性制約。
要解決這兩個問題就只要兩步即可,但當然在正規項目中不建議使用,要遵循MVC和PCR-0(1.只有一個入口檔案;2.在類檔案中不能使用直接實現方法的寫法;3.命名空間與絕對路徑一致)法則,這隻是一個偏門技巧。
解決方案
-
在include檔案後,用spl_autoload_unregister()把自動載入的函數登出掉;
如:spl_autoload_unregister(‘\\Test\\Loader::autoload‘);
但在運用完第三方類的時候要馬上把之前的自動載入函數運行一次,不然其他方法載入不了會報錯。
\main\Test1::test();
spl_autoload_register(‘\\Test\\Loader::autoload‘);
2. 第三方類要加上單獨的命名空間,不然在使用的時候會,include類會以當前的命名空間來使用。如果載入類不是在跟當前命名空間同一個目錄,就會報錯。
貼其中一個類代碼:
namespace Test;class Factory{public static function createDatabase(){$db = new Database();Register::set(‘db1‘,$db);include BASEDIR.‘/Test1.php‘;spl_autoload_unregister(‘\\Test\\Loader::autoload‘);\main\Test1::test();spl_autoload_register(‘\\Test\\Loader::autoload‘);return $db;}}
最終還是叮囑不建議程式用這個,盡量遵守面向過程的編程方法。
php命名空間自動載入後使用單獨類include使用