您的位置:

PHPStorm Debug: 如何有效地调试PHP代码

一、安装Xdebug

Xdebug是一款可以帮助我们调试PHP代码的扩展,它可以追踪PHP代码的执行,显示执行过程中的变量、函数以及类的调用情况等等。其最大的优点是支持与多种IDE进行集成,如PHPStorm、NetBeans、Eclipse等。

在PHPStorm中安装Xdebug并与IDE集成需要进行以下步骤:

1、添加Xdebug扩展到PHP的配置文件中

zend_extension="/path/to/xdebug.so"
xdebug.remote_enable=true
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.idekey=PHPStorm

其中,最后一行的xdebug.idekey的值需要与后文PHPStorm IDE设置中的Key值相同。

2、设置PHPStorm IDE

在File -> Settings -> Languages & Frameworks -> PHP -> Debug中进行配置,选择Xdebug作为默认的调试器,设置IDE key值为之前添加到php配置文件中的值,如下图所示:

二、设置断点

在本地server中的PHP代码中设置断点是开始调试过程的第一步。按下Ctrl+F8,或者从主菜单选择Toggle Breakpoint -> Line Breakpoint来在代码行上设置断点。断点被设置在行的左侧,如下图所示:

三、执行代码

在执行PHP代码的时候,断点会使程序执行到此处停止。在右上角的调试栏中,我们可以看到当前代码的调用堆栈,包括函数、类、变量等信息。

可以在左侧的Call Stack窗口中查看当前代码所在的栈帧:

在Variables窗口中,我们可以查看当前作用域中所有变量的值:

四、调试功能

在PHPStorm中,我们可以使用以下调试功能:

1、Step Into(F7): 进入被调用函数或方法,并显示该函数或方法的源代码:

2、Step Over (F8):执行当前行代码,停止在下一个断点上,并显示断点的源码:

3、Step Out (shift+F8):在当前函数或方法执行完毕后,结束当前函数或方法的执行,并返回调用他的地方,可以查看到函数或方法的返回值:

五、变量监控

在调试大型PHP应用程序时,可能同时引用了多个变量,需要监视和分析每个变量的细节。变量监控能够方便地查看每个变量,并显示变量更改信息。

PHPStorm支持对变量进行监控的代码发布在Xdebug使用手册中,如下所示:

function xdebug_monitor($val) {
   xdebug_start_trace('/tmp/trace.log');
   var_dump($val);
   xdebug_stop_trace();
}

六、多进程调试

当PHP代码运行在多进程环境中(如nginx、apache、fpm、cli),PHPStorm也支持调试。在Xdebug扩展中设置debug模式和idekey值,然后可以在IDE的edit configuration中设置多个server调试。

七、动态调试

PHPStorm支持动态调试,即在运行时修改代码、添加或删除断点等。这需要在debug模式下设置inline mode,并将xdebug.idekey的值设置正确。

zend_extension="/path/to/xdebug.so"
xdebug.remote_enable=true
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.idekey=PHPStorm
xdebug.profiler_enable=1
xdebug.profiler_output_name=foobar
xdebug.remote_mode=req
xdebug.remote_handler=dbgp
xdebug.remote_connect_back=0
xdebug.remote_autostart=0
xdebug.remote_log=/tmp/xdebug.log
xdebug.show_local_vars=1
xdebug.trace_format=0
xdebug.collect_params=2
xdebug.collect_return=1
xdebug.show_mem_delta=0
xdebug.max_nesting_level=200
xdebug.cli_color=0
xdebug.profiler_aggregate = 0
xdebug.profiler_enable_trigger = 1
xdebug.profiler_output_dir = "/tmp"
xdebug.remote_mode = jit
xdebug.remote_host = 127.0.0.1
xdebug.remote_port = 9000
xdebug.start_with_request=yes
xdebug.remote_autostart=1
xdebug.idekey=PHPSTORM
xdebug.remote_log="log/xdebug.log"
xdebug.remote_handler=dbgp
xdebug.remote_connect_back=0
xdebug.remote_cookie_expire_time=-1
xdebug.show_exception_trace=0
xdebug.show_error_trace=0
xdebug.collect_params=2
xdebug.collect_return=1
xdebug.show_local_vars=1
xdebug.trace_format=2
xdebug.max_nesting_level=250
xdebug.cli_color=1
xdebug.profiler_output_name='xdebug-profile-cgi-%H'