here.php
· 1012 B · PHP
Неформатований
<?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
1 | <?php |
2 | |
3 | /** |
4 | * Returns caller class/file name, function and line where current |
5 | * |
6 | * Potentially doesn't cover all cases, but is simple and pretty handy for use in frameworks. |
7 | * |
8 | * @param bool $as_array result as array or string in this format: `<file|class>:<func>():<line>` |
9 | * @return string|array |
10 | */ |
11 | function here(bool $as_array = false): string|array |
12 | { |
13 | $trace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
14 | return $as_array |
15 | ? [ |
16 | 'from' => $trace[1]['class'] ?? $trace[0]['file'], |
17 | 'function' => $trace[1]['function'], |
18 | 'line' => $trace[0]['line'], |
19 | ] |
20 | : sprintf( |
21 | '%s%s%s():%s', |
22 | $trace[1]['class'] ?? $trace[0]['file'], |
23 | $trace[1]['type'] ?? '::', |
24 | $trace[1]['function'], |
25 | $trace[0]['line'] |
26 | ); |
27 | } |
28 | |
29 | // Usage: |
30 | class MyClass { |
31 | public function test(): string { |
32 | return here(); |
33 | } |
34 | } |
35 | echo (new MyClass)->test(); // MyClass->test():4 |
36 |