在PHP函数中获取调用作用域


Get calling scope in a PHP function?

可以从被调用的函数内部访问调用环境的作用域吗?

例如,我想在日志功能中访问__LINE__,但它需要是调用环境中的__LINE__。我也想有一些方法调用get_defined_vars()来获得调用者变量。

在这两个例子中,它都节省了额外的参数。

这可能吗?

没有办法得到调用者的变量,但是可以得到它们的参数。这很容易用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");

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

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

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

有点像,但不是在生产代码中使用的明智方式。

在这两个例子中,它都节省了额外的参数。

这会使你的代码很难理解,因为你会破坏函数隐含的封装。

话虽如此,您可能会使用全局变量?