Last active
March 24, 2023 08:38
-
-
Save anthonyaxenov/9627503669c0318757bc1243b1573c0d to your computer and use it in GitHub Desktop.
[PHP] Get caller class, function and line number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Returns caller class/file name, function and line where current | |
* | |
* Potentially doesn't cover all cases, but is simple and pretty handy for use in frameworks. | |
* | |
* @param bool $as_array result as array or string in this format: `<file|class>:<func>():<line>` | |
* @return string|array | |
*/ | |
function here(bool $as_array = false): string|array | |
{ | |
$trace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 2); | |
return $as_array | |
? [ | |
'from' => $trace[1]['class'] ?? $trace[0]['file'], | |
'function' => $trace[1]['function'], | |
'line' => $trace[0]['line'], | |
] | |
: sprintf( | |
'%s%s%s():%s', | |
$trace[1]['class'] ?? $trace[0]['file'], | |
$trace[1]['type'] ?? '::', | |
$trace[1]['function'], | |
$trace[0]['line'] | |
); | |
} | |
// Usage: | |
class MyClass { | |
public function test(): string { | |
return here(); | |
} | |
} | |
echo (new MyClass)->test(); // MyClass->test():4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment