← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 2 of 10

PHP Debugging with Xdebug

What is Xdebug?

Xdebug is a PHP extension that adds debugging, profiling, and code-analysis capabilities the language doesn't have on its own, and is close to a standard tool for serious PHP development.

Example: What is Xdebug?

php
<?php
echo extension_loaded('xdebug') ? "Xdebug is loaded" : "Xdebug not installed";
echo "\nAdds debugging, profiling, and code analysis to PHP";
?>

Stack Traces and Var Dumps

With Xdebug enabled, PHP's normal error output gets replaced with much richer messages -- including a full stack trace and nicely formatted variable dumps -- that make tracking down the source of a bug considerably faster.

Example: Stack Traces and Var Dumps

php
<?php
function level3() { throw new Exception("Something broke"); }
function level2() { level3(); }
function level1() { level2(); }
try {
    level1();
} catch (Exception $e) {
    echo $e->getTraceAsString();
}
?>

Step Debugging

Step debugging lets you set a breakpoint in your IDE, run the script, and have execution pause exactly there so you can inspect variables and step through subsequent lines one at a time instead of guessing from logs.

Example: Step Debugging

php
<?php
$x = 5;
$y = 10;
$sum = $x + $y; // set a breakpoint here in your IDE to inspect $x and $y
echo $sum;
?>

Code Coverage

Code coverage tracking records which lines actually executed during a test run, revealing gaps in your test suite -- code paths nobody is testing at all.

Example: Code Coverage

php
<?php
function isEven($n) {
    if ($n % 2 === 0) {
        return true;
    }
    return false; // a test suite might never exercise this line
}
echo isEven(4) ? "even" : "odd";
?>

Performance Profiling

Xdebug's profiler records how much time and memory each function call consumes, producing a file you can load into a tool like KCachegrind to visually spot the actual bottleneck instead of guessing.

Example: Performance Profiling

php
<?php
function slowFunction() {
    for ($i = 0; $i < 100000; $i++) {}
}
$start = microtime(true);
slowFunction();
echo "Took " . round(microtime(true) - $start, 4) . "s -- a profiler shows exactly where time goes";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.