PHP打印调用堆栈的三种方法

一、debug_print_backtrace()



二、debug_backtrace()



三、Exception类中的getTraceAsString()成员函数返回一个调用堆栈



一、debug_print_backtrace()
//调用函数parent_func
function child_func() {
parent_func();
}



//调用grandparent_func
function parent_func() {
grandparent_func();
}



//打印调用堆栈
function grandparent_func() {
debug_print_backtrace();
}



//主函数调用
child_func();
#0 grandparent_func() called at [D:\wamp\www\temp.php:10]
#1 parent_func() called at [D:\wamp\www\temp.php:5]
#2 child_func() called at [D:\wamp\www\temp.php:19]



二、debug_backtrace()
//调用函数parent_func
function child_func() {
parent_func();
}



//调用grandparent_func
function parent_func() {
grandparent_func();
}



//打印调用堆栈
function grandparent_func() {
var_dump(debug_backtrace());
}



//主函数调用
child_func();
D:\wamp\www\temp.php:15:
array (size=3)
0 =>
array (size=4)
‘file’ => string ‘D:\wamp\www\temp.php’ (length=27)
‘line’ => int 10
‘function’ => string ‘grandparent_func’ (length=16)
‘args’ =>
array (size=0)
empty
1 =>
array (size=4)
‘file’ => string ‘D:\wamp\www\temp.php’ (length=27)
‘line’ => int 5
‘function’ => string ‘parent_func’ (length=11)
‘args’ =>
array (size=0)
empty
2 =>
array (size=4)
‘file’ => string ‘D:\wamp\www\temp.php’ (length=27)
‘line’ => int 19
‘function’ => string ‘child_func’ (length=10)
‘args’ =>
array (size=0)
empty

三、getTraceAsString()
Exception类中的getTraceAsString()成员函数返回一个调用堆栈



//调用函数parent_func
function child_func() {
parent_func();
}



//调用grandparent_func
function parent_func() {
grandparent_func();
}



//打印调用堆栈
function grandparent_func() {
$e = new Exception;
var_dump($e->getTraceAsString());
}



//主函数调用
child_func();
D:\wamp\www\temp.php:16:string ‘#0 D:\wamp\www\temp.php(10): grandparent_func()
#1 D:\wamp\www\temp.php(5): parent_func()
#2 D:\wamp\www\temp.php(20): child_func()
#3 {main}’ (length=162)



Category php