Chapter 22. Debugging

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. —Brian W. Kernighan

No matter how good a programmer you are, you will at some point find that there are at least one or two errors in your code—sometimes because you hit the wrong key while typing, other times because you misunderstood how a function worked, and sometimes even because you were coding at 5 a.m. It is important to understand the arsenal that PHP puts at your disposal.

The Most Basic Debugging Technique

If you are experiencing a problem with your script, the time-honored way to figure out what's going on is to sprinkle your code with lots of print statements. This is a technique that few people will admit they use, but I can assure you it is widespread—and not just in the PHP programming world! Consider this following script:

    $foo = "bar";
    $wombat = somefunc($foo);
    print "After somefunc()\n";
    $wombat2 = somefun2($wombat);
    print "After somefunc2()\n";

If we found that somefunc2() was causing a problem that caused PHP to silently exit the script, we would see the output "After somefunc()", but not "After somefunc2()", which points to the problem function.

This method has benefits: it is easy to use, and will generally find the problem through trial and error. The downsides are clear, though: you need to edit your script quite heavily to make use of the print statements, ...

Get PHP in a Nutshell 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.