PHP 错误处理 debug_print_backtrace() 函数


PHP 错误处理 debug_print_backtrace() 函数允许您查看导致错误或特定程序点的代码序列。一个接一个调用的文件和函数列在显示的 “回溯” 中。

这有助于开发人员识别错误的潜在来源。开发过程中的调试是它的主要用途。此功能使查找和更正代码中的错误变得更加简单。

语法

以下是 PHP 错误处理 debug_print_backtrace() 函数的语法 -

void debug_print_backtrace ( int $options, int $limit )

参数

以下是 debug_print_backtrace() 函数的参数 -

意义
$options (可选) 用于为以下选项指定位掩码: DEBUG_IGNORE_BACKTRACE_ARGS (是否删除所有函数/方法参数和 “args” 索引以保留内存。
$limit (可选)限制可以创建的堆栈帧的数量。默认情况下,将报告所有堆栈帧 (limit=0)。

 

返回值

debug_print_backtrace() 函数不返回任何值。

PHP 支持版本

debug_print_backtrace() 函数首次引入于核心 PHP 5 中,在 PHP 7 和 PHP 8 中继续轻松运行。

示例 1

这是 PHP 错误处理 debug_print_backtrace() 函数的基本示例。代码遵循调用函数的顺序。当程序运行时,将调用函数 one()two() three()。在 three() 中,debug_print_backtrace() 按顺序显示这些函数调用的列表。

<?php
   function one() {
      two();
   }

   function two() {
      three();
   }

   function three(){
      debug_print_backtrace();
   }
   one();
?>

以下是以下代码的结果 -

#0  three() called at [C:\user\WWW\index.php:7]
#1  two() called at [C:\user\WWW\index.php:3]
#2  one() called at [C:\user\WWW\index.php:13]

示例 2

在下面的 PHP 代码中,我们将使用带有 $limit 参数的 debug_print_backtrace() 函数。此程序将回溯跟踪中的堆栈帧数限制为 2。此示例说明如何使用 $limit 参数限制回溯跟踪中显示的函数数量。

<?php
   function one() {
      two();
   }

   function two() {
      three();
   }

   function three() {
      // 将回溯限制为2帧
      debug_print_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
   }

   one();
?> 

这将生成以下输出 -

#0  three() called at [C:\user\WWW\index.php:7]
#1  two() called at [C:\user\WWW\index.php:3]
 

示例 3

该程序展示了如何使用 DEBUG_BACKTRACE_IGNORE_ARGS 选项从回溯中删除函数参数。在此示例中,DEBUG_BACKTRACE_IGNORE_ARGS 选项用于隐藏回溯跟踪中的函数参数。

<?php
   function one($a) {
      two($a, 20);
   }

   function two($b, $c) {
      three($b, $c);
   }

   function three($d, $e) {
      // 忽略回溯中的函数参数
      debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
   }

   one(10);
?> 

这将创建以下输出 -

#0  three() called at [C:\user\WWW\index.php:7]
#1  two() called at [C:\user\WWW\index.php:3]
#2  one() called at [C:\user\WWW\index.php:15]

示例 4

在下面的示例中,我们将展示如何将 debug_print_backtrace() 函数与类方法和对象一起使用。该程序跟踪类和对象函数中的调用序列,以展示 debug_print_backtrace() 如何显示完整的跟踪。

<?php
   class Test {
      public function one() {
         $this->two();
      }

      private function two() {
         $this->three();
      }

      protected function three() {
         // 显示所有详细信息的回溯
         debug_print_backtrace();
      }
   }

   $obj = new Test();
   $obj->one();
?> 

以下是上述代码的输出 -

#0  Test->three() called at [C:\user\WWW\index.php:8]
#1  Test->two() called at [C:\user\WWW\index.php:4]
#2  Test->one() called at [C:\user\WWW\index.php:18]