Get scope of call in PHP function?

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

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

In both examples, this saves the need to have an additional argument.

Is it possible?

+6
source share
2 answers

It is not possible to get the variables of callers, but you can get their arguments. This is easy to do 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 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 completely move the trace.

0
source

Sorting, but not as it would be wise to use in production code.

In both examples, this saves the need to have an additional argument.

This will make your code very hard to understand, as you break the implied encapsulation that the function has.

With all that said, can you use a global variable for this?

0
source

Source: https://habr.com/ru/post/892779/


All Articles