tags:

views:

324

answers:

2

PHP's assert statement doesn't behave like most other languages.

assert('return false'); actually evaluates the string and then asserts its result (false).

Instead of comparing the paramter to true, it goes through the extra step of examining the argument, and if it's a string evaluating it, then performing the comparison.

Very strange indeed.

My problem is not in understanding the behaviour, my problem is coming up with a valid reason for this behaviour, esp. since you now have to do the extra mental work of thinking... "does that evaluate to a string?".

Thanks

+1  A: 

I would guess it simply is so they didn't need to special case a particular part of the language. I believe that in PHP if you treat a string like an expression is it evaluated automatically. This way you can do things like just pass the name of a function and try to "call" it and it works (function pointers without the pointers :-P).

EDIT: see Jakob's answer for a relevant quote from the PHP docs about assert as well.

Evan Teran
What do you mean "if you treat a string like an expression is it evaluated automatically"? Can you give an example? This sounds totally crazy and wrong, unless I am misunderstanding you. As far as I know, the above is a special feature of assert.
rjmunro
+8  A: 

The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

from http://www.php.net/manual/en/function.assert.php

Jakob Stoeck
good find in the docs. spells it right out.
Evan Teran