Xdebug 3 已經正式釋出, 不僅在效能上提升, 在設定上也變得簡單許多。
今天來介紹如何在 VSCode 上使用 XDebug 來偵錯 PHP 程式。
環境
- Windows 10
- VSCode v1.52.0
- PHP v7.4.12
- XDebug v3.0.0
PHP 在本機上的環境變數設定,請參考 如何整合設定 PHP 的開發環境至 Visual Studio Code
PHP 加上 Xdebug
下載 PHP XDebug,請務必下載對應 PHP 的版本
php.ini
設定檔需加上 XDebug 的設定來開啟 debug 模式
zend_extension 請設定您的 PHP XDebug 的檔案位置
[xdebug]
zend_extension="D:\_devlib\php\xdebug\php_xdebug-3.0.0-7.4-vc15-x86_64.dll"
xdebug.mode=debug
xdebug.start_with_request=yes
; xdebug 3 版 port 預設為 9003, 若想維持與 2 版一樣的 9000 port 則可變更 client_port 的值
;xdebug.client_port = 9000
XDebug v3 的設定是不是精簡許多?
確認 PHP 是否正確掛載 XDebug 的 extension
$ php -v
顯示應會如下 (必須出現 with Xdebug …)
PHP 7.4.12 (cli) (built: Oct 27 2020 17:18:47) ( ZTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Xdebug v3.0.0, Copyright (c) 2002-2020, by Derick Rethans
安裝 VSCode 的 PHP Debug 套件
- PHP Debug by Felix Becker
或者是安裝 PHP Productive Pack 套件包增加生產力
VSCode 的偵錯設定
在 VSCode 開啟 PHP 專案,點 "執行" 選擇 "新增組態",選擇 "PHP"
即會自動產生對應程式語言的偵錯設定檔 .vscode/launch.json
由於目前使用 XDebug 的版本是 v3.0.0,預設的 port 要改成 9003
才行
{
"version": "0.2.0",
"configurations": [
{
"name": "Listen for XDebug",
"type": "php",
"request": "launch",
"port": 9003
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 9003
}
]
}
執行偵錯
下圖為一個簡單的 PHP 檔案,前面有紅點為指定偵錯的中斷點
- 先在程式加上偵錯中斷點
- 執行偵錯
- Listen for XDebug (偵錯監聽中,需在終端機或網站執行到此行程式才會觸發偵錯)
- Lunch currently open script (即會在 focus 的 PHP 程式啟動偵錯)
- 偵錯步驟 (繼續/不進入函式/逐步執行/跳離函式/重新啟動/停止)
在偵錯的面板上即可看到偵錯的訊息
例如此例在程式跳到第 5 行時, $x 的變數值為 "VSCode + PHP Debug mode!"
偵錯 PHP 就是這麼簡單!