在PHP函数中获取调用范围?

Ann*_*nan 6 php scope

我可以从被调用的函数中访问调用环境的范围吗?

例如,我想访问__LINE__日志记录功能,但它需要__LINE__来自调用环境.我还想通过某种方式调用get_defined_vars()来获取调用者变量.

在这两个例子中,它节省了必须有一个额外的参数.

这可能吗?

mik*_*n32 1

无法获取调用者的变量,但您可以获取他们的参数。这很容易通过以下方式完成debug_backtrace()

<?php

class DebugTest
{
    public static function testFunc($arg1, $arg2) {
        return self::getTrace();
    }

    private static function getTrace() {
        $trace = debug_backtrace();
        return sprintf(
            "This trace function was called by %s (%s:%d) with %d %s: %s\n",
            $trace[1]["function"],
            $trace[1]["file"],
            $trace[1]["line"],
            count($trace[1]["args"]),
            count($trace[1]["args"]) === 1 ? "argument" : "arguments",
            implode(", ", $trace[1]["args"])
        );
    }
}

echo DebugTest::testFunc("foo", "bar");
Run Code Online (Sandbox Code Playgroud)

运行该程序,我们得到以下输出:

This trace function was called by testFunc (/Users/mike/debug.php:23) with 2 arguments: foo, bar
Run Code Online (Sandbox Code Playgroud)

debug_backtrace()返回一个数组;元素 0 是调用该函数本身的函数,因此我们在示例中使用元素 1。您可以使用循环一路返回跟踪。