首頁  >  文章  >  後端開發  >  PHP include檔案包含路徑搜尋問題的總結

PHP include檔案包含路徑搜尋問題的總結

黄舟
黄舟原創
2017-06-25 10:59:422180瀏覽

首先我們來看php官方手冊中對include的檔案搜尋原則的描述:

Files for including are first looked for in each include_path entry relative to the current working directory, 
and then in the directory of current script. E.g. if your include_path is libraries , current working directory is  , 
you included  and there is include "b.php"  in that file,   is first looked in   
and then in  . If filename begins with ./  or ../ , it is looked only in the current working directory.

尋找包含檔案的順序先是在目前工作目錄的相對的include_path 下尋找,然後是目前執行腳本所在目錄相對的include_path 下尋找。例如 include_path 是 . ,目前工作目錄是  ,腳本中要 include 一個   且在該文件中有一句 include "b.php" ,則尋找   的順序先是  ,然後是  ,然後是  ,然後是  ,然後是  。如果檔案名稱以 ./  或 ../  開始,則只在目前工作目錄相對的 include_path 下尋找。

所以如下圖所示的檔案結構

----a.php

#----include/b.php

----include/c.php

 其中a.php

<?php
include &#39;include/b.php&#39;;
?>
-----------------------
b.php
<?php
include &#39;c.php&#39;;
include &#39;include/c.php&#39;;
?>

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

c.php

<?php
echo &#39;c.php&#39;;
?>

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

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

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

<?php
define(&#39;ROOT_PATH&#39;,dirname(FILE));
include ROOT_PATH.&#39;/c.php&#39;;
?>

不同的檔案包含方式,程式的執行效能比較具體可以參考此文

<script type="text/
javascript
"><!--
google_ad_client = "ca-pub-1944176156128447";
/* cnblogs 首页横幅 */
google_ad_slot = "5419468456";
google_ad_width = 728;
google_ad_height = 90;
//--></script>
<script type="text/javascript" src=" 
</script>

以上是PHP include檔案包含路徑搜尋問題的總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn