描述:公司項目PHP用作中間轉發層(接收http請求,用 socket跟c++做通信),由于代碼沒有用到框架,這些東西自然就是之前的人自己寫的。最近需要對這個底層進行優化,于是便看了下這部分的代碼。
目的:這塊代碼的主要作用是把主目錄下的所有插件類一次性全部加載進來。當使用尚未被定義的類(class)和接口(interface)時自動去加載。通過注冊自動加載器,腳本引擎在 PHP 出錯失敗前有了最后一個機會加載所需的類。
實現方法:主要用到PHP函數__autoload()
詳細:
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); set_include_path($_SERVER['Root_Path'] . '/libs' . PATH_SEPARATOR . $_SERVER['Root_Path'] . '/lib' . PATH_SEPARATOR . get_include_path() ); if (!function_exists('__autoload')) { function __autoload($className) { ///優化包含路徑 $path=_getRootPath($className); $revpath=strtr($className, '_', '/'). '.php'; $rootpath=$path.$revpath; file_exists($rootpath)?include($rootpath):@include($revpath); } } /** *得到根路徑* */ function _getRootPath($classname) { $pearpath=$_SERVER["PHP_PEAR_PATH"].'/'; $libpath=$_SERVER['Root_Path'] . '/lib/'; $libspath=$_SERVER['Root_Path'] . '/libs/'; if(strpos($classname,'Zend_')===0) return $pearpath; ///zend 框架路徑 if(strpos($classname,'DB_')===0 || strpos($classname,'Interface_')===0 || strpos($classname,'Others_')===0 || strpos($classname,'Pay_')===0 || strpos($classname,'PHPMailer_')===0 ) return $libspath; return $libpath; }
其中_getRootPath($classname)函數獲取的是類名文件所在的真實目錄,根據類名的頭字段判斷類在哪個目錄下;
如果類能在這些目錄下找到,類在使用前就會被加載。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。
【網站聲明】本站除付費源碼經過測試外,其他素材未做測試,不保證完整性,網站上部分源碼僅限學習交流,請勿用于商業用途。如損害你的權益請聯系客服QQ:2655101040 給予處理,謝謝支持。