一、安裝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'
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/195632.html