Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track variable changes in PHP

Good day.

I've been working on project that contains many variables and sessions and where most of the job is done "under the hood" and via ajax.

The problem is that I try to debug my project and I just can't find any way to track and log changes that're made to a certain variable.

I've been trying to use firephp and xdebug but they don't show when changes where made to the variable, only its final value.

Any solution?

like image 615
shultz Avatar asked Oct 21 '22 08:10

shultz


2 Answers

XDebug can track the variable changes, just enable xdebug.collect_assignments and xdebug.collect_params, so when you generate trace log file, you should see the changes.

Example configuration:

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.

Then before or after you assign the variable for the first time, start tracing the code by adding this into your PHP code:

xdebug_start_trace();

then optionally add xdebug_stop_trace(); at the end where you think it already happened.

Then check the file generated in configured directory (specified by xdebug.trace_output_dir). If the file is large, filter it by specific variable using grep, e.g.

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

or filter it into the smaller file by: grep pattern trace-log.xt > smaller.log.txt.


Another alternative would be to use phpdbg.

like image 63
kenorb Avatar answered Oct 24 '22 04:10

kenorb


May be logged decorator can help you?

If you want to track some instance variables you can wrap them around with decorator that implements same interface. And into decorator methods you can write debug level log and then deligate workflow to original variables saved as decorator object field.

like image 31
Ivan Velichko Avatar answered Oct 24 '22 04:10

Ivan Velichko