Relative and Absolute Path
I want to reference a file that is in my root director开发者_Go百科y , The problem is that this file is used by several other PHP scripts that can be 2 or three paths deep.
I can reference this by
'../database_sql/dbconnect.php' ; 1 deep
'../../database_sql/dbconnect.php' ; 2 deep
'../../../database_sql/dbconnect.php' ; 3 deep
My question is how can I reference this root folder file without knowing how deep the path is ie: not using ../../../
etc
Two solutions:
The first is to define a constant whose value is the root directory:
// in a file in a your root directory:
define('ROOT', dirname(__DIR__));
// in other files:
include ROOT . '/file/relative/to/the/root.php';
The second is to use the include_path:
// 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';
An alternative solution (little more work) is to go Object Oriented and implement an autoloader.
精彩评论