工欲善其事必先利其器。如果你想看懂框架,如果你想快速找到代碼中的疑難問題,你首先要學會單步調(diào)試跟蹤代碼。
之前一直都是使用zendstudio + zend debugger + Firefox調(diào)試PHP的,。可是zend debugger在windows下不支持高版本的PHP(好像是可以支持到5.2),后來開始使用phpstorm和xdebug調(diào)試。
安裝PhpStorm
官方地址:https://www.jetbrains.com/phpstorm/
安裝PHP Xdebug擴展
xdebug官網(wǎng):
https://xdebug.org/
擴展下載地址:
http://pecl.php.net/package/xdebug
https://xdebug.org/download.php
如果你不能確定你需要下載哪個版本的擴展,你可以借助xdebug官方提供的工具,輸入phpinfo即可獲取需要下載的版本。
https://xdebug.org/wizard.php
修改PHP配置文件 php.ini
[Xdebug]
zend_extension=C:\webserver\server\php-5.6.9\ext\php_xdebug-2.3.3-5.6-vc11-x86_64.dll
;允許遠程IDE調(diào)試
xdebug.remote_enable=on
;遠程IDE所在HOST和PORT
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
;開啟遠程調(diào)試自動啟動
xdebug.remote_autostart = Off
;可以是任意Key,這里設(shè)定為PHPSTORM
xdebug.idekey = "PHPSTORM"
;開啟自動跟蹤
xdebug.auto_trace = On
xdebug.trace_output_dir="C:\webserver\xdebug"
;把執(zhí)行情況的分析文件寫入到指定目錄中
xdebug.profiler_enable=on
xdebug.profiler_output_dir="C:\webserver\xdebug"
這里你可以看到所有配置項的解釋:
https://xdebug.org/docs/all_settings
輸出phpinfo看下擴展是否安裝成功。
配置PHPStorm
Ctrl+Alt+S 調(diào)出配置界面,輸入xdebug搜索配置位置。
注意端口號是否和php.ini中設(shè)置的一致,默認為9000。
配置DBGP Proxy
安裝firefox 調(diào)試插件
The easiest Xdebug
This extension for Firefox was built to make debugging with an IDE easier. You can find the extension at https://addons.mozilla.org/en-US/firefox/addon/the-easiest-xdebug/.
其中的原理你可以參看https://xdebug.org/docs/remote
調(diào)試PHP
在PHPStorm中創(chuàng)建項目,在代碼中設(shè)置斷點。點擊phpstorm run>start listening或者右上角的小電話開啟監(jiān)聽。進入需要調(diào)試的頁面,點擊火狐右上角的“臭蟲”開始調(diào)試,你也可以在此點擊關(guān)閉調(diào)試。
到此,你就可以愉快的進行斷點調(diào)試跟蹤代碼了!
分析代碼性能
你也可以利用WinCacheGrind或者QCacheGrind軟件和xdebug生成的cachegrind.out文件分析PHP腳本的性能。
下載地址:
http://sourceforge.net/projects/wincachegrind/
http://sourceforge.net/projects/qcachegrindwin/
你也可以使用其他工具分析,參照這里:
https://xdebug.org/docs/profiler
參考資料
- xdebug幫助文檔: https://xdebug.org/docs/
- IDE遠程調(diào)試:https://xdebug.org/docs/remote
注意的坑
- 注意PHPstorm的版本和xdebug的版本
phpstorm能進入調(diào)試一直無法下一步,然后發(fā)現(xiàn)phpstorm版本太低2018.1.6發(fā)行的版本, 而xdebug是2019年發(fā)布的,然后我就選擇了一個2018.1.6時間之前發(fā)布的xdebug就好了