php include()函數測試分析

來源:互聯網
上載者:User

include_path 下尋找,然後是當前運行指令碼所在目錄相對的 include_path 下尋找。例如 include_path 是 . ,當前工作目錄是 /www/ ,指令碼中要 include 一個 include/a.php教程  並且在該檔案中有一句 include "b.php" ,則尋找 b.php  的順序先是 /www/ ,然後是 /www/include/ 。如果檔案名稱以 ./  或者 ../  開始,則只在當前工作目錄相對的 include_path 下尋找。

所以如下所示的檔案結構

----a.php

----include/b.php

----include/c.php

 其中a.php

<?php

include 'include/b.php';

?>

-----------------------

b.php

<?php

include 'c.php';

include 'include/c.php';

?>

--------------------------

c.php

<?php

echo 'c.php';

?>

--------------------------

都能正確運行,說明b.php中兩種不同包含路徑都是可行的,根據include尋找包含檔案的方式都能找到c.php。

但是最好的方式還是使用絕對路徑,如果使用了絕對路徑,php核心就直接通過路徑去載入檔案而不用去include path逐個搜尋檔案,增加了代碼執行效率

<?php

define('root_path',dirname(__file__));

include root_path.'/c.php';

?>


結論:

顯然include 後面路徑的格式和php的include path 對程式效能都是存在影響的,include 效能從慢到快的排序是

include 'a.php' < include './a.php' < include '/fullpath/a.php

在代碼中,使用絕對路徑include檔案是最好的選擇,因為這樣php核心就直接通過路徑去載入檔案而不用去include path逐個搜尋檔案。

所以我們最好在項目的公用檔案中定義一個項目根目錄絕對路徑的常量,然後所有的include的路徑前都帶上這個常量,這樣項目中所有的include使用的都是絕對路徑,既提高程式效能,也減少了相對路徑帶來的煩惱。

參考代碼(來自emlog):

define('emlog_root', dirname(__file__));

include emlog_root . '/config.php';

如果你的項目中已經大量使用include 'test.php'  這樣格式的相對路徑且不好大量修改,那麼請盡量減少php include path中的路徑以提高一定的include效能。因為include path中的路徑越少,php搜尋檔案的時間也越少。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.