2013-03-23 46 views
1

任何人都可以幫助我獲取函數調用的目錄的基名?我的意思是:PHP獲取文件的名稱,其中函數調用

文件/root/system/file_class.php

function find_file($dir, $file) { 
    $all_file = scandir($dir); 
    .... 
} 

function does_exist($file) { 
    $pathinfo = pathinfo($file); 
    $find = find_file($pathinfo["dirname"], $pathinfo["basename"]); 
    return $find; 
} 

文件/root/app/test.php

$is_exist = does_exist("config.php"); 

在/根/應用程序我有文件「配置。 php,system.php「。你知道如何獲得does_exist()所調用的目錄嗎?在函數find_file()自變量$dir很重要,因爲scandir()函數需要目錄路徑來掃描。我的意思是,當我想檢查文件config.php我不需要寫/root/app/config.php。如果我沒有在$file參數中提供完整路徑,$ pathinfo [「dirname」]將是"."。我試過在file_find()函數中使用dirname(__file__),但它返回的目錄爲/root/system而不是/root/app,它在does_exist()函數調用的目錄中。

我需要創建這些功能,因爲我不能使用file_exists()函數。

找到的解決辦法

我使用debug_backtrace()獲得,用戶調用函數的最近的文件和行號。例如:

function read_text($file = "") { 
    if (!$file) { 
     $last_debug = next(debug_backtrace()); 
     echo "Unable to call 'read_text()' in ".$last_debug['file']." at line ".$last_debug['line']."."; 
    } 
} 

/home/index.php

16 $text = read_text();

示例輸出:Unable to call 'read_text()' in /home/index.php at line 16.

感謝。

回答

1

使用任何的PHP魔術常量

__DIR__ 
__FILE__ 

http://php.net/manual/en/language.constants.predefined.php

或者使用真實路徑( 「./」);

要定義自己的常數路徑:

定義( 「mypath中」,真實路徑( 「./」) 「/ DIR/DIR /」;

然後,您可以從任何地方這個調用此mypath中。代碼(文件)包含在內。

相關問題