pol*_*l_b 91 php function-calls
有没有办法找出,PHP中的函数从哪里调用?例:
function epic()
{
fail();
}
function fail()
{
//at this point, how do i know, that epic() has called this function?
}
Run Code Online (Sandbox Code Playgroud)
rom*_*mac 123
你可以用debug_backtrace()
.
例:
<?php
function epic( $a, $b )
{
fail( $a . ' ' . $b );
}
function fail( $string )
{
$backtrace = debug_backtrace();
print_r( $backtrace );
}
epic( 'Hello', 'World' );
Run Code Online (Sandbox Code Playgroud)
输出:
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
)
)
)
Run Code Online (Sandbox Code Playgroud)
Bol*_*ock 25
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()...
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*zuk 17
我发现最快最简单的解决方案
public function func() { //function whose call file you want to find
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
}
$trace: Array
(
[0] => Array
(
[file] => C:\wamp\www\index.php
[line] => 56
[function] => func
[class] => (func Class namespace)
[type] => ->
)
)
Run Code Online (Sandbox Code Playgroud)
我在联想笔记本电脑上测试速度:Intel Pentiom CPU N3530 2.16GHz,RAM 8GB
global $times;
$start = microtime(true);
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
$times[] = microtime(true) - $start;
Run Code Online (Sandbox Code Playgroud)
结果:
count($times): 97
min: 2.6941299438477E-5
max: 10.68115234375E-5
avg: 3.3095939872191E-5
median: 3.0517578125E-5
sum: 321.03061676025E-5
the same results with notation without E-5
count($times): 97
min: 0.000026941299438477
max: 0.0001068115234375
avg: 0.000033095939872191
median: 0.000030517578125
sum: 0.0032103061676025
Run Code Online (Sandbox Code Playgroud)
mar*_*rix 15
所以,如果你仍然真的不知道如何,这里解决方案:
$backtrace = debug_backtrace();
echo 'Mu name is '.$backtrace[1]['function'].', and I have called him! Muahahah!';
Run Code Online (Sandbox Code Playgroud)
尝试下面的代码。
foreach(debug_backtrace() as $t) {
echo $t['file'] . ' line ' . $t['line'] . ' calls ' . $t['function'] . "()<br/>";
}
Run Code Online (Sandbox Code Playgroud)