[英]Relative and Absolute Path
我想引用根目錄中的文件,問題是該文件被其他幾個深度為2或3個路徑的PHP腳本使用。
我可以通過引用
'../database_sql/dbconnect.php' ; 1 deep
'../../database_sql/dbconnect.php' ; 2 deep
'../../../database_sql/dbconnect.php' ; 3 deep
我的問題是如何在不知道路徑深度的情況下如何引用此根文件夾文件,即:不使用../../../
等
兩種解決方案:
首先是定義一個常量,其值為根目錄:
// in a file in a your root directory:
define('ROOT', dirname(__DIR__));
// in other files:
include ROOT . '/file/relative/to/the/root.php';
第二種是使用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';
另一種解決方案(需要更多工作)是面向對象並實現自動加載器 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.