Chapter 13. Debugging and Testing

Despite developers’ best efforts, no code is ever perfect. You will inevitably introduce a bug that impacts the production behavior of your application or causes an end user distress when something doesn’t operate as expected.

Properly handling errors within your application is critical.1 However, not every error your application throws is expected—or even catchable. In these circumstances, you must understand how to properly debug your application—how to track down the offending line of code so it can be fixed.

Among the first steps any PHP engineer uses to debug their code is the echo statement. Without a formal debugger, it’s common to see development code littered with echo "Here!"; statements so the team can track where things might be broken.

The Laravel framework has made similar functionality popular and easily accessible while working on new projects by exposing a function called dd() (short for “dump and die”). This function is actually provided by the Symfony var-dumper module and works effectively in both PHP’s native command-line interface and when leveraging an interactive debugger. The function itself is defined as follows:

function dd(...$vars): void
{
    if (!in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !headers_sent()) {
        header('HTTP/1.1 500 Internal Server Error');
    }

    foreach ($vars as $v) {
        VarDumper::dump($v);
    }

    exit(1);
}

The preceding function, when used in a Laravel application, will print the contents of any variable you ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.