2011-09-05 259 views
0

我想引用一個位於我的根目錄下的文件,問題是這個文件被其他幾個PHP腳本使用,這些腳本的深度可能是2或3個路徑。相對和絕對路徑

我可以

'../database_sql/dbconnect.php' ; 1 deep 
'../../database_sql/dbconnect.php' ; 2 deep 
'../../../database_sql/dbconnect.php' ; 3 deep 

引用這個我的問題是我怎麼能引用此根文件夾的文件不知道的路徑有多深,即:不使用../../../

+0

而且*根目錄*你的意思是什麼?像Linux'/ root'或「其他幾個PHP腳本」的公共根目錄? –

回答

3

兩個解決方案:

第一個是定義一個常數,其值是根目錄:

// in a file in a your root directory: 
define('ROOT', dirname(__DIR__)); 

// in other files: 
include ROOT . '/file/relative/to/the/root.php'; 

第二是使用包含路徑:

// in a file in your root directory: 
set_include_path(dirname(__DIR__) . PATH_SEPARATOR . get_include_path()); 

// in other files: 
// PHP will search in include_path 
include 'file/relative/to/the/root.php'; 
3

另一種解決方案(多一點的工作)的去面向對象和實現autoloader

+1

+1,自動加載定義了要走的路 – arnaud576875