2012-11-25 26 views
0

我有一個目錄/文件樹如下:PHP多態根要求

index.php 

/frame/main_class.php 
/frame/func/function_1.php 
/frame/func/function_1.php 
/cfg/config.php 

//index.php 

require('frame/main_class.php'); 
new main_class; 

//frame/main_class.php 

class main_class{ 
    public function __construct(){ 
     require('func/function_1.php'); 
     require('func/function_2.php'); 
     require('cfg/config.php'); 
    } 
} 

怪異的部分是,它的工作原理。也許這是遲到了,我有一個愚蠢的時刻,但不應該「要求('cfg/config');」寫成「require('../ cfg/config.php');」 ?

如果是使用index.php的根,那麼「require('func/function_1.php');」不應該工作,對吧?

我有四重檢查遠程服務器,認爲可能有一個零星的文件或兩個......沒有。 兩人如何要求陳述有不同的基本路徑.....?

有誰知道可能導致這種情況發生的代碼片段?我正在使用一些$ _SERVER變量,但我似乎沒有改變他們中的任何一個....!?


"Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing."明確地說include dirname(__FILE__) . '/path/to/file.php';避免了這種混亂。 - DCoder

Link to PHP Manual on "dirname".

+2

[「*文件是根據給定的文件路徑包含的,或者如果沒有給出,則指定include_path,如果在include_path中找不到該文件,include將最終檢查**調用腳本自己的目錄**和失敗之前的**當前工作目錄。*「](http://us.php.net/manual/en/function.include.php)明確指出include include dirname(__ FILE__)。 '/path/to/file.php';'避免了這種混淆。 – DCoder

+0

啊,這使得完整和完美的感覺。所以它檢查include_path並找不到它,因此它檢查腳本路徑並找到函數。對於cfg文件,它很可能從ini中設置的include_path中找到它。 –

+1

對我來說,'怪異'一點就是這行代碼在index.php文件中工作:'require('main_class.php');'當它在一個名爲frame的文件夾中時,它是如何工作的? – Dale

回答

3

PHP引擎將尋找當前目錄所要求的文件,但它也將尋找他們的INCLUDE_PATH定義的路徑列表。如果包含路徑列出腳本運行的路徑,則給定的代碼將起作用。如果不是那麼它不會。

出於這個原因,依靠包含路徑來解析包含文件的路徑並不是一個好主意。你應該改爲完整的路徑。

+0

我可以問一個暗淡的問題嗎?從哪裏的完整路徑? –

+0

從根。你可以很容易地用__DIR__和__FILE__魔術常數 – GordonM

+0

得到有趣的,謝謝! –