這很奇怪,有沒有人總結過一個結論呢?包含include()的相對路徑時,PHP會檢查哪些目錄?
有時它也會檢查包含文件的目錄。
但有時沒有。
d:\測試\ 1.PHP
<?php
include('sub\2.php');
d:\測試\ 2.PHP
<?php
include('3.php');
凡3.php
是在相同的目錄作爲2.php
。
上述作品,但爲什麼呢?當前的目錄應該是D:\test
,但它仍然可以找到3.php,這是D:\test\sub
更多故事(最終)
大約一年前,我遇到了這個問題,然後我結束了硬編碼像下面固定它:
的common.php:
if (file_exists("../../../Common/PHP/Config.inc"))
include('../../../Common/PHP/Config.inc');
if (file_exists("../../Common/PHP/Config.inc"))
include('../../Common/PHP/Config.inc');
if (file_exists("../Common/PHP/Config.inc"))
include('../Common/PHP/Config.inc');
if (file_exists("Common/PHP/Config.inc"))
include('Common/PHP/Config.inc');
凡Config.inc
是在同一個目錄中Common.php
好問題!我可以在Windows和Linux上確認這一點。我不知道這是爲什麼。 – 2010-03-13 12:03:25
關於你的最後一個例子,如果「Config.inc」和「Common.php」在同一個目錄下,那麼這可以簡化爲include(dirname(__ FILE __)。/ Config.inc');工作,而不管'include_path'和哪個文件「Common.php」包含在內。如果沒有機會在include_path中找到Config.inc(通常包括當前目錄),那麼你可以簡單地調用include,Config.inc,雖然這可能效率較低,首先搜索「include_path」(失敗)。 – MrWhite 2015-02-10 17:55:35
在你的第一個例子中,我假設「D:\ test \ 2.php」應該是「D:\ test \ sub \ 2.php」? (否則'include('sub \ 2.php');'永遠不會工作。) – MrWhite 2015-02-10 17:58:47