2011-09-05 258 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