【问题标题】:PHP Get Basename of File Where Function CalledPHP获取函数调用的文件的基本名称
【发布时间】:2013-03-23 20:07:24
【问题描述】:

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

文件/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"] 将是"."。我尝试在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.

谢谢。

【问题讨论】:

    标签: php dirname


    【解决方案1】:

    使用任何 PHP 魔术常量

    __DIR__
    __FILE__
    

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

    或者使用realpath("./");

    定义你自己的常量路径:

    define("MYPATH", realpath("./") ."/dir/dir/";

    然后,您可以从包含此代码(文件)的任何地方调用此 MYPATH。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2011-09-09
      • 1970-01-01
      相关资源
      最近更新 更多