【问题标题】:How to get the absolute path of the calling file in a function that's called in PHP?如何在 PHP 中调用的函数中获取调用文件的绝对路径?
【发布时间】:2010-03-13 11:34:25
【问题描述】:

file.php:

call()...

如何在call()中获取file.php的绝对路径?

注意call()可能定义在另一个文件中。

another.php:

function call(){..}

file.php:

include(path_to_another.php);
call();

【问题讨论】:

    标签: php path


    【解决方案1】:

    除了debug_backtrace没有办法

    function whatever() {
        $t = debug_backtrace();
        echo "called from {$t[0]['file']}";
    }
    

    【讨论】:

    • 为了获取到根目录的相对路径,我使用了$_SERVER['REQUEST_URI']。使用我的函数root(),我可以轻松获取到根目录的'../../ 路径。 @user187291,你的回答让我开始了;谢谢!
    【解决方案2】:

    除了 James Brooks 的回答和 Brettcus 的观察,如果你需要获取 调用文件basename 你可以这样做:

    $backtrace = debug_backtrace();
    $file_name = basename($backtrace[0]['file']);
    

    【讨论】:

      【解决方案3】:

      您也可以像这样获取文件的basename

      basename(__FILE__);
      

      希望这会有所帮助!

      【讨论】:

      • FILE 只会引用包含文件,而不是调用它的文件。
      猜你喜欢
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2014-01-19
      • 2018-11-30
      • 1970-01-01
      • 2021-10-18
      • 2019-07-29
      相关资源
      最近更新 更多