AnnanFay
AnnanFay

Reputation: 9749

Get calling scope in a PHP function?

Can I access the scope of the calling environment from within a called function?

For example, I would like to access __LINE__ in a logging function but it needs to be the __LINE__ from the calling environment. I would also like to have some way of calling get_defined_vars() to get the callers variables.

In both examples it saves having to have an extra argument.

Is this possible?

Upvotes: 6

Views: 1348

Answers (2)

miken32
miken32

Reputation: 42713

There's no way to get the callers' variables, but you can get their arguments. This is easily done with 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");

Running this program, we get this output:

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

debug_backtrace() returns an array; element 0 is the function in which the function itself was called, so we use element 1 in the example. You can use a loop to travel all the way back up the trace.

Upvotes: 1

troelskn
troelskn

Reputation: 117507

Sort of, but not in a way that would be wise to use in production code.

In both examples it saves having to have an extra argument.

It would make your code very hard to understand, as you would break the implied encapsulation that a function has.

That all said, you might use a global variable for this?

Upvotes: 0

Related Questions