如何跟踪PHP中的变量变化


How to track variable changes in PHP

大家好。

我一直在项目中工作,其中包含许多变量和会话,其中大部分工作都是通过ajax完成的。

问题是我试着调试我的项目,我就是找不到任何方法来跟踪和记录对某个变量所做的更改。

我一直在尝试使用firephp和xdebug,但他们不显示何时更改了变量,只有它的最终值。

解决方案吗?

XDebug可以跟踪变量的变化,只启用xdebug.collect_assignmentsxdebug.collect_params,所以当您生成跟踪日志文件时,您应该可以看到这些变化。

示例配置:

xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.trace_output_dir="/var/log/xdebug" ; string: Directory where the tracing files will be written to.

然后在您第一次赋值变量之前或之后,通过将以下代码添加到PHP代码中来开始跟踪代码:

xdebug_start_trace();

然后可选地在你认为已经发生的地方添加xdebug_stop_trace();

检查配置目录(xdebug.trace_output_dir指定)下生成的文件。如果文件很大,使用grep通过特定变量过滤它,例如

grep --color=auto variable trace-log.xt

或通过:grep pattern trace-log.xt > smaller.log.txt .

将其过滤到较小的文件中。

另一种选择是使用phpdbg

可能登录装饰师能帮到你吗?

如果你想跟踪一些实例变量,你可以用实现相同接口的装饰器把它们包裹起来。在decorator方法中,您可以编写调试级别的日志,然后将工作流委托给保存为decorator对象字段的原始变量。