網頁

8月 16, 2010

XAMPP - Xdebug的簡介及安裝

最近在學一些網頁設計會用到的工具
說到Xdebug的好處在於程式有錯誤時可以列出發生錯誤的程式碼進入點
以下面程式碼為例(此程式碼由網站製作學習誌轉載)
<?php
function test($var)
{
   $var->display();
}

$abc = 123;
test($abc);
?>
在尚未開啟Xdebug時,當PHP程式發生錯誤,會產生下面的文字訊息
Fatal error: Call to a member function display() on a non-object in 
C:\XAMPP\htdocs\index.php on line 4

但如果開啟Xdebug之後,錯誤訊息將變成下列
Fatal error: Call to a member function print() on a non-object in C:\XAMPP\htdocs\index.php on line 4
Call Stack
# Function Location
1 {main}() C:\XAMPP\htdocs\index.php:0
2 test() C:\XAMPP\htdocs\index.php:8

經過上面的比較,可以看到Xdebug開啟後,
對於錯誤程式碼的部份提供了完整的程式進入點,
藉此可以快速知道函式最早是在何處被呼叫的!對於小程式來說可能沒感覺,
但是當專案非常大,程式碼有幾十萬行時,Xdebug就變得非常方便找尋錯誤。

此外,對於變數未定義的錯誤,Xdebug會找不到問題,這是由於PHP變數不需宣告
直接加上$即可使用的關係,這時不彷在<?php的下方加上
error_reporting(E_ALL);
這樣Xdebug就能把未定義變數的錯誤找出來了!

以下將教您如何開啟Xdebug,首先開啟php.ini檔,找到下面幾個敘述句
;zend_extension = "C:\xampp\php\ext\php_xdebug.dll"
;xdebug.profiler_enable = 0
;xdebug.profiler_output_dir = "C:\xampp\tmp"
;xdebug.profiler_output_name = "xdebug_profile.%p"
;xdebug.remote_enable = 0
;xdebug.remote_handler = "dbgp"
;xdebug.remote_host = "localhost"
;xdebug.remote_port = 9000
;xdebug.trace_output_dir = "C:\xampp\tmp"
將分號都拿掉並改成以下敘述
zend_extension = "C:\xampp\php\ext\php_xdebug.dll"
xdebug.profiler_enable = on
xdebug.profiler_output_dir = "C:\xampp\xdebug"
xdebug.profiler_output_name = "xdebug_profile.%p"
xdebug.remote_enable = On
xdebug.remote_handler = "dbgp"
xdebug.remote_host = "localhost"
xdebug.remote_port = 9000
xdebug.trace_output_dir = "C:\xampp\xdebug"
最後將apache重新啟動,打開phpinfo()頁面,若看到php版本資訊下方有

This program makes use of the Zend Scripting Language Engine:
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
with Xdebug v2.0.6-dev, Copyright (c) 2002-2009, by Derick Rethans

代表Xdebug已經成功啟動!可以快樂使用了
請注意Xdebug在專案開發完畢之後記得要關掉,這樣可以加快網頁讀取速度!

0 評論:

張貼留言