DEV Community

David Kanekanian
David Kanekanian

Posted on

E4 - Using PHP Debugging Tools in Visual Studio Code

If you have not already setup XDebug in Visual Studio Code, please refer to the earlier stage, Setting up PHP debugging in Visual Studio Code. This post assumes you have XDebug installed and the launch configuration is created.

1. Copy this code into a file index.php as a starting point.

<?php
function makeMessage($name, $age)
{
    // Make the name have a capital first letter
    $first = strtoupper($name[0]);
    // Make the rest have small letters.
    $end = strtolower(substr($name, 1));
    // Save the two parts in the name variable.
    $name = $first . $end;


    // Ensure the age is in the valid range.
    assert(0 < $age && $age < 1000, "age must be between 1 and 999");


    // Return the final message.
    return "$name is $age years old!";
}


$message = makeMessage("david", 99);
echo $message;

?>
Enter fullscreen mode Exit fullscreen mode

2. Click on line 18 where $message is set and add a breakpoint from Run > Toggle Breakpoint (hotkey F9). A red circle will appear on the left side of it.
setting a breakpoint

3. Start debugging on the Run tab by clicking Run (hotkey F5) in Listen for XDebug mode.
run tab

4. Open this page in your browser (make sure Apache is started.) You should see the browser will not show anything and the Visual Studio Code window will gain focus.
Alt Text

5. Use the step into button to investigate inside the makeMessage() function.
step into button

6. Use the step over button for a few lines. You will see the state of local variables in the Run tab when they are assigned values.
step over button
variables in run tab

7. Enter a debug command in the Debug tab (View > Debug Console) to check the first letter in $name. You can enter any valid expression here.
debug console

8. Press Continue to let the execution return to normal speed.
continue execution button

9. When you return to the browser, you will see that the output is ‘David is 99 years old!’

Parent topic: Example 4

Top comments (0)