PHP获取函数调用的文件的基本名称

时间:2013-03-23 20:07:25

标签: php dirname

任何人都可以帮我获取函数调用目录的基本名称?我的意思是:

file /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");

在/ root / app下我有文件“config.php,system.php”。你知道如何获取调用does_exist()的目录吗?在函数find_file()中,参数$dir很重要,因为scandir()函数需要扫描目录路径。我的意思是,当我想检查文件config.php时,我不需要写/root/app/config.php。如果我没有在$file参数中提供完整路径,则$ pathinfo [“dirname”]将为"."。我尝试在dirname(__file__)函数中使用file_find(),但它返回目录/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 个答案:

答案 0 :(得分:1)

使用任何PHP魔术常量

__DIR__
__FILE__

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

或使用realpath(“./");

定义自己的常量路径:

define(“MYPATH”,realpath(“./”)。“/ dir / dir /”;

然后,您可以从包含此代码(文件)的所有位置调用此MYPATH。