Making a mistake with a variable name sometimes inadvertently creates never-ending loops. The result of a never-ending loop is that the web browser eventually times out and alerts the user that the web server isn't responding to an HTTP request.
The following loop never ends, and no output is produced:
for($counter=0; $counter<10; $Counter++) myFunction( );
$counter is never incremented. Instead, another variable,
$Counter, is, so
$counter is always less than 10. Common bugs result from subtle changes in variable names through changing case, omitting or including underscores, or simple typographic errors.
Never-ending loops can also produce unexpected output. The following loop can render thousands of greetings in a web browser in a very short time:
for($counter=0; $Counter<10; $counter++) echo "<br>hello";
These errors can sometimes be detected by setting the PHP error-reporting level to a higher sensitivity. Adding the following code fragment to the top of each PHP script or to a file included with the
require directive reports undefined variable errors:
This forces variables to be declared by assigning a value before they can be used. Consider the following example:
error_reporting(E_ALL); for($counter=0; $Counter<10; $counter++) echo "<br>hello";
This produces an unending number of warning messages stating:
Warning: Undefined variable: Counter in /var/lib/apache/htdocs/winestore/a.php on line 2
The script keeps on running, because it's only a warning. A custom error handler can be incorporated that stops the script when an error or warning is encountered by using the
set_error_handler( ) function. We discuss error handlers in Chapter 10.