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?
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.
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" );
$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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With