小滕的博客

小滕的技术点滴

如何获取PHP一个请求的生命周期的调用栈?

3 months ago · 1 MIN READ

在PHP当中我们如何知道一次请求下去背后的调用栈呢?比如说加载了哪些文件?执行了哪些方法?这些方法在调用栈的中当时传入的参数是什么?

PHP为我们提供了 debug_backtrace 函数来说去上面的信息,下面是我在 laravel 框架的使用及输出:

Route::get('/', function () {
    return debug_backtrace();
});

输出结果(精简版):

[{
        "file": "/Users/xiaoteng/work/www/laravel5.8/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php",
        "line": 53,
        "function": "Illuminate\\Pipeline\\{closure}",
        "class": "Illuminate\\Pipeline\\Pipeline",
        "object": {},
        "type": "->",
        "args": [{
            "attributes": {},
            "request": {},
            "query": {},
            "server": {},
            "files": {},
            "cookies": {},
            "headers": {}
        }]
    },
    {
        "file": "/Users/xiaoteng/work/www/laravel5.8/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
        "line": 104,
        "function": "Illuminate\\Routing\\{closure}",
        "class": "Illuminate\\Routing\\Pipeline",
        "object": {},
        "type": "->",
        "args": [{
            "attributes": {},
            "request": {},
            "query": {},
            "server": {},
            "files": {},
            "cookies": {},
            "headers": {}
        }]
    },
    {
        "file": "/Users/xiaoteng/work/www/laravel5.8/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
        "line": 151,
        "function": "then",
        "class": "Illuminate\\Pipeline\\Pipeline",
        "object": {},
        "type": "->",
        "args": [{}]
    },
    {
        "file": "/Users/xiaoteng/work/www/laravel5.8/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
        "line": 116,
        "function": "sendRequestThroughRouter",
        "class": "Illuminate\\Foundation\\Http\\Kernel",
        "object": {},
        "type": "->",
        "args": [{
            "attributes": {},
            "request": {},
            "query": {},
            "server": {},
            "files": {},
            "cookies": {},
            "headers": {}
        }]
    },
    {
        "file": "/Users/xiaoteng/work/www/laravel5.8/public/index.php",
        "line": 55,
        "function": "handle",
        "class": "Illuminate\\Foundation\\Http\\Kernel",
        "object": {},
        "type": "->",
        "args": [{
            "attributes": {},
            "request": {},
            "query": {},
            "server": {},
            "files": {},
            "cookies": {},
            "headers": {}
        }]
    },
    {
        "file": "/Users/xiaoteng/work/www/laravel5.8/server.php",
        "line": 21,
        "args": [
            "/Users/xiaoteng/work/www/laravel5.8/public/index.php"
        ],
        "function": "require_once"
    }
]

该函数返回的调用栈数组详细的给出了整个PHP生命周期的调用栈信息,非常全面。另外,还有一个 debug_print_backtrace 函数,该函数直接打印出调用栈信息,因为Laravel的一次请求的调用栈信息太多,这里就不给出了(知道为什么Laravel的性能不行的原因了吧)。

···

xiao teng



备案号:皖ICP备14012032号-5