參考資料:https://www.bilibili.com/video/BV1Qx411f7pF
一、PHP程式的除錯
這裡對PHP程式除錯的IDE選擇的是PHPStorm
,因為PHPStorm應該是PHP語言當前最受歡迎的程式碼編輯環境,而且對各種補全以及生成PHPdoc功能的支援都非常好。
1. 單個PHP程式的除錯
首先依次選擇 File -> Settings -> PHP (CLI Interpreter欄原本是空的):

然後選擇自己的php.exe即可(如果沒有顯示的需要先設定php環境變數):

選擇之後儲存確定即可。
我當前使用的php整合環境是Wampserver64(Apache+PHP+MySQL),具體版本如下:

在我的這個PHP執行環境中,就已經自帶有xdebug
外掛了,即對應的.dll檔案包含在每個php版本資料夾中的zend_ext目錄下,如下所示(如沒有xdebug
外掛則需要先去下載):


然後我們需要開啟php目錄下的php.ini,新增上如下程式碼:


這裡的zend_extension
的值為剛才xdebug.dll檔案的地址,而我這裡不是剛剛那個檔案是因為我將它複製到了ext目錄下並修改了它的命名。
然後即可編輯php檔案,然後在合適的地方打上斷點:

然後右鍵檔案選擇除錯該檔案即可:

最終我們終於實現了單步除錯,並且在下面的debug tab中檢視到各個變數的內容了:

2. PHP框架程式碼的除錯
這裡我所使用的PHP框架是thinkphp6.x
,其他的框架應該也是類似的。
這裡我們需要再次修改原來的php.ini檔案,如下所示:

後面的這幾個引數在PhpStorm
中除錯單檔案也可以看到,我們把它們如上加入到php.ini檔案中即可。
此後我們再轉到PhpStorm中,選擇 File->Settings->Debug:

這裡將Debug port修改為php.ini檔案中xdebug.remote_port
所設定的埠,最後我們只需在php.ini檔案中再新增上一句:

這句意味著自動開啟xdebug,如果設定了這個屬性,則我們可以在任意時刻進行斷點除錯,當然這也意味著執行效率有一定的降低,因為需要產生額外的除錯資訊,這一點和其他語言的分別以執行模式和除錯模式執行是類似的,因此這個屬性可以看情況進行關閉掉以提高效能(不需要除錯時關閉即可)。
tips:修改了php.ini檔案的配置,需要重新啟動Apache等服務才可以生效,我這裡重啟了WampServer的所有服務。
重新啟動服務後,我們輸入:php think run -H '自己的虛擬域名'
(這是thinkphp的啟動命令)來啟動tp6專案:

然後使用瀏覽器訪問這個生成的url:http://api.tp6.com:8000/
可以發現彈出這個視窗:

點選accept即可,然後發現php程式停在了斷點:

終於,我們實現了對php框架程式碼的單步除錯,框架中使用的變數等資訊也可以檢視了,這比使用var_dump
等列印的方式一次一調的方式強太多了!
二、JavaScript程式的除錯
這裡使用到的程式碼除錯工具為Chrome,首先先編寫一小段js程式:

然後使用瀏覽器開啟這個html檔案:

此時按下F12開啟除錯工具,選擇Sources欄:

選擇了對應的檔案後,我們可以看到剛剛編寫的js程式碼,然後我們可以在對應的行號上打上斷點,如:

然後重新整理頁面,可以看到js程式停在了斷點:

此時,我們可以在右邊欄檢視變數等各種資訊:

至此我們已實現了對js程式的除錯。
三、總結
本文實現了對PHP程式及JavaScript程式的單步除錯,雖然就PHP和JavaScript程式而言,我們大多數情況都可以使用列印大法,如:console.log()
、echo
、var_dump()
來進行除錯,但遇到一些棘手的問題時,單步除錯可以一次性解決大部分的bug,大大縮短解決問題的時間,應該是不可缺少的重要工具,因此特地開貼記錄在PHP和JavaScript專案中這一重要工具的配置方法。