Приглашаем посетить
Спорт (www.sport-data.ru)

Overview of Programming Errors

Table of Contents
Previous Next

Overview of Programming Errors

PHP, being a scripting language, offers us an opportunity to spot errors as the program is interpreted, while it also poses a problem since the scripts are often executed on a server and therefore not as accessible for debugging as traditional stand-alone programs. However, the class of errors that can be spotted while the script is interpreted is often just a small subset of the programming errors that creep into scripts. Some common programming errors encountered while coding PHP scripts are:

Let us take a closer look at these errors now.

Syntax Errors

Syntax errors are the most common and easily detected category of errors. These errors occur due to incorrect use of language constructs. Occurrence of syntax errors has significantly changed between PHP3 and PHP4. This is because, with PHP3, each line was interpreted as it was encountered, whereas with PHP4, the statements are compiled before they are executed.

With PHP3 a single successful run of a program does not guarantee that all syntactic errors have been weeded out. Most often special code-paths, taken by the script, unearth syntax errors that have not yet been discovered. To illustrate this, let us look at the following PHP3 script:

    <?php
    //Simple_Leap.php

    if ($year % 4) {
        // simplified test for a non-leap year
        echo("February has 28 days");
    } else {
        echo("February has 29 days');
    }
    ?>

This code would execute just fine when $year has a non-leap year value, which is three times out of four. However, in the code block handling the leap year case, there is a syntax error – the echo statement's argument string begins with a double-quotation mark but is closed by a single-quotation mark. This is an obvious and easily traceable error that can be fixed quite easily. However, in the absence of a good testing strategy, it can cause the program to fail at an unexpected point.

Common syntax errors involve omitting matching parentheses and other punctuation, misspelled keywords, omitting the $ sign before variables, and so on. Most syntax errors are typographical or are caused by novice programmers yet to attain a sufficient comfort level with the syntax. Usually syntax errors can be traced to the line they occur, since the parser reports the error with the line number. However, this is not always the case, as can be seen in the example below:

    <?php
    //Sample.php
    for ($count = 0; $count <= 10; ++$count)
        echo($count)
    ?>
    <h2>Sample program</h2>
    <?php
    echo("Program ends ...");
    ?>

Here the parser does not report an error at line 4 where we missed the semi-colon after the echo statement.

Semantic Errors

Semantic errors are a class of errors that might be syntactically correct, and therefore might go unnoticed by the parser. However, when the execution reaches the erroneous statement, the execution might fail. Such errors are quite common with function invocations, since PHP does not match function argument signatures against invocation arguments. In other words, if a function defined to take two arguments, is invoked with just one argument, the parser does not detect it but the execution fails.

Another example is using the wrong operator for an operation. Since PHP is a loosely typed language, most operators often work on most variable types; however, the result may not make sense.

Applying the multiplication operator to two character strings would result in a zero since PHP would convert both the strings to a value of zero and multiply them. This is true in cases where the string does not look like a number. If a string looks like a number and is used in a numeric context then the number that can be extracted from the string will be used. For example, the code shown below returns "404" to the browser:

    <?php
    //String_Mult.php
    echo("101 Dalmations" * "4 Beatles");
    ?>

Let us look at another common semantic error with the switch statement:


    <?php
    //Sample_Switch.php
    $color = "peach";

    switch ($color) {
    case "peach":
        echo("Peach is my favorite color <br>");

    case "pink":
        echo("Pink is my favorite color");
    }
    ?>

This would produce the unexpected result of both pink and peach being the favorite color. This is syntactically a valid construct, that is this might have been useful to us if we wanted to express a logical OR condition between the two cases (see below). The lack of a break statement after the first echo statement caused the execution to fall through and execute the next statement.

Logical Errors

Logical errors are those that have very little to do with the language constructs themselves. In fact, logical errors occur with code that is syntactically and semantically correct. Logical errors occur when the programmer writes code hoping it would do something whereas the code turns out to do something else. The classic example is misspelt variable names that take a bad turn, as PHP does not require variables to be declared before hand. These errors are hard to trace unless you have good test cases. Let us take a look at the following code for an example of a logical error:

    <?php
    //Logical_Error.php
    for ($i = 1; $i < 10; $i++)
        print("Number:" . $i . "<br>");
    ?>

Here the programmer intended the script to print the numbers 1 to 10, inclusive. However, since the comparison operator was < as opposed to <= the last comparison 10 < 10 did not succeed and only the numbers 1 to 9 were printed.

Important 

The foreach construct available in PHP4 prevents such an error from creeping in when dealing with arrays. As a rule of thumb it is a good idea to use the foreach constructor when iterating over arrays.

Environmental Errors

Environmental errors are a result of factors extraneous to the program and often go undetected by test cases designed to catch syntax, semantic, and logical errors. In fact, these errors crop up only when external entities such as files, network connections, and input data assume a form or behave in a manner unexpected by the program. For example, consider a script which opens files for write operations on the server's local disk. This script might work fine in a development environment, but will fail in a production environment where disk access privileges might be much more restrictive than on the development workstation.

Another example is a program that expects input data to be in a particular language, but when deployed in a new locale goes completely haywire. The only way to prevent environmental errors is to ensure that interactions with external entities are validated and the code checked. Further more, such interactions require structured error handling in the event that the results of such interactions are not in accordance with the program's expectations.

Often certain functions (mostly arcane) or arguments to functions are not available on all platforms that PHP runs on, for example, the socket() function used to create a network socket takes AF_UNIX as a protocol argument on most UNIX (or UNIX-like) systems but the option is not supported on Microsoft Windows (see Chapter 13 for details). However, more often than not it is quite possible to write code that does not use these platform-specific features.


Table of Contents
Previous Next