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 ...
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.