Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get calling scope in a PHP function?

Tags:

scope

php

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?

like image 883
AnnanFay Avatar asked Jul 14 '11 17:07

AnnanFay


People also ask

How can access variable function in PHP?

Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.

How do you call a function in PHP?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var ); call_user_func( $var1 , "fun_function" );

What does $globals mean in PHP?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

Does PHP have function scope?

Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function.


1 Answers

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.

like image 135
miken32 Avatar answered Oct 10 '22 23:10

miken32