Can someone give me a good reason for why assert in php behaves the way it does?

StackOverflow https://stackoverflow.com/questions/648237

  •  22-07-2019
  •  | 
  •  

Question

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 parameter 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?".

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top