詳解PHP架構自動載入類的檔案原理

來源:互聯網
上載者:User
這篇文章主要為大家詳細介紹了PHP架構自動載入類檔案原理,具有一定的參考價值,感興趣的小夥伴們可以參考一下

描述:公司項目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)函數擷取的是類名檔案所在的真實目錄,根據類名的頭欄位判斷類在哪個目錄下;

如果類能在這些目錄下找到,類在使用前就會被載入。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.