【问题标题】:Get the __FILE__ constant for a function's caller in PHP在 PHP 中获取函数调用者的 __FILE__ 常量
【发布时间】:2009-11-26 14:57:28
【问题描述】:

我知道 PHP 中的 __FILE__ 魔术常量会变成当前执行文件的完整路径和文件名。但是有没有一种方法可以获得函数调用文件的相同信息?例如:

//foo.php:
include "bar.php";
call_it();

//bar.php
function call_it() {
    echo "Calling file: ".__CALLING_FILE__;
}

这将输出Calling file: ....../foo.php

我知道没有__CALLING_FILE__ 魔法常数或魔法常数来处理这个问题,但有没有办法获得这些信息?最简单的解决方案将是理想的(例如,使用堆栈跟踪将非常 hacky)但最后我只需要它工作。

【问题讨论】:

  • 我希望这可以在没有回溯的情况下完成

标签: php


【解决方案1】:

您应该查看堆栈跟踪以执行此类操作。 PHP有一个函数叫debug_backtrace

include "bar.php";
call_it();

//bar.php
function call_it() {
   $bt =  debug_backtrace();

   echo "Calling file: ". $bt[0]['file'] . ' line  '. $bt[0]['line'];
}

希望对你有帮助

在相同的原理上,您会发现debug_print_backtrace 很有用,它做同样的事情,但 php 自己处理所有信息的格式化和打印。

【讨论】:

  • 好吧,所以我想 PHP 堆栈跟踪实用程序比我预期的要友好,这似乎是做我想做的最干净的方法。
【解决方案2】:

debug_backtrace()是你的朋友

这就是我们用来转储 current 行的完整堆栈跟踪的方法。要根据您的情况调整它,请忽略 $trace 数组的顶部。

class Util_Debug_ContextReader {
    private static function the_trace_entry_to_return() {
        $trace = debug_backtrace();

        for ($i = 0; $i < count($trace); ++$i) {
            if ('debug' == $trace[$i]['function']) {
                if (isset($trace[$i + 1]['class'])) {
                    return array(
                        'class' => $trace[$i + 1]['class'],
                        'line' => $trace[$i]['line'],
                    );
                }

                return array(
                    'file' => $trace[$i]['file'],
                    'line' => $trace[$i]['line'],
                );
            }
        }

        return $trace[0];
    }

    /**
     * @return string
     */
    public function current_module() {
        $trace_entry = self::the_trace_entry_to_return();

        if (isset($trace_entry['class']))
            return 'class '. $trace_entry['class'];
        else
            return 'file '. $trace_entry['file'];

        return 'unknown';
    }

    public function current_line_number() {
        $trace_entry = self::the_trace_entry_to_return();
        if (isset($trace_entry['line'])) return $trace_entry['line'];
        return 'unknown';
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-14
    • 2017-07-14
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2010-12-23
    相关资源
    最近更新 更多