php:确定从何处调用函数
2022-08-30 07:35:00
有没有办法找出PHP中的函数是从哪里调用的?例:
function epic()
{
fail();
}
function fail()
{
//at this point, how do i know, that epic() has called this function?
}
有没有办法找出PHP中的函数是从哪里调用的?例:
function epic()
{
fail();
}
function fail()
{
//at this point, how do i know, that epic() has called this function?
}
您可以使用 debug_backtrace()
。
例:
<?php
function epic( $a, $b )
{
fail( $a . ' ' . $b );
}
function fail( $string )
{
$backtrace = debug_backtrace();
print_r( $backtrace );
}
epic( 'Hello', 'World' );
输出:
Array
(
[0] => Array
(
[file] => /Users/romac/Desktop/test.php
[line] => 5
[function] => fail
[args] => Array
(
[0] => Hello World
)
)
[1] => Array
(
[file] => /Users/romac/Desktop/test.php
[line] => 15
[function] => epic
[args] => Array
(
[0] => Hello
[1] => World
)
)
)
function fail()
{
$backtrace = debug_backtrace();
// Here, $backtrace[0] points to fail(), so we'll look in $backtrace[1] instead
if (isset($backtrace[1]['function']) && $backtrace[1]['function'] == 'epic')
{
// Called by epic()...
}
}