O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Making Assertions

The assert() function is a clever one that works along the same lines as our print statements, but it only works if a certain condition is not matched. Essentially, assert() is used to say "This statement must be true—if it isn't, please tell me." For example:

    print "Stage 1\n";
    assert(1 =  = 1);
    print "Stage 2\n";
    assert(1 =  = 2);
    print "Stage 3\n";

Here we have two assert()s, with the first call asserting that one must be equal to one, and the second call asserting that one must be equal to two. As it is impossible to redefine constants like 1 and 2, the first assert() will always evaluate to true, and the second will always evaluate to false. Here is the output from the script:

    Stage 1
    Stage 2
    Warning: assert() [http://www.php.net/function.assert]: Assertion failed
            in /home/paul/sandbox/php/assert.php on line 5
    Stage 3

The first assert() is not seen in the output at all because it evaluated to true, whereas the second assert() evaluated to false, so we get a warning about an assertion failure. However, script execution carries on so that we see "Stage 3" after the assertion failure warning. As long as assertions evaluate to true, they have no effect on the running of the script, which means you can insert them for debugging purposes and not have to worry about taking them out once you are finished debugging.

If you are worried about your assertions slowing execution down, which, although the speed hit will be minimal, is still a valid concern, you can disable execution ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required