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

        1. 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 [C:\Users\2023020701\Desktop\test.php:32]
#1  parent_func() called at [C:\Users\2023020701\Desktop\test.php:28]
#2  child_func() called at [C:\Users\2023020701\Desktop\test.php:39]

        2. debug_backtrace()

//调用函数two
function one($str1, $str2)
{
    two("Glenn", "Quagmire");
}
//调用three
function two($str1, $str2)
{
    three("Cleveland", "Brown");
}
//打印调用堆栈
function three($str1, $str2)
{
    print_r(debug_backtrace(0,1));
}
//主函数调用
one("Peter", "Griffin");


Array
(
    [0] => Array
        (
            [file] => C:\Users\2023020701\Desktop\test.php
            [line] => 18
            [function] => three
            [args] => Array
                (
                    [0] => Cleveland
                    [1] => Brown
                )
        )

    [1] => Array
        (
            [file] => C:\Users\2023020701\Desktop\test.php
            [line] => 12
            [function] => two
            [args] => Array
                (
                    [0] => Glenn
                    [1] => Quagmire
                )
        )

    [2] => Array
        (
            [file] => C:\Users\2023020701\Desktop\test.php
            [line] => 29
            [function] => one
            [args] => Array
                (
                    [0] => Peter
                    [1] => Griffin
                )
        )
)

        3. 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)


        

冷暖自知一抹茶ck
请先登录后发表评论
  • 最新评论
  • 总共0条评论