6 ms·
Yes and no. You will see the boolean keywords (they aren't actually constants) is the case making sure actually is a boolean, not a string/int. $x = "";
by nuclear_eclipse 18y ago
Yes and no. You will see the boolean keywords (they aren't actually constants) is the case making sure actually is a boolean, not a string/int.
$x = "";
if ( $x == false ) {} #yes
if ( $x === false ) {} #no
Edit: this is very useful for allowing a string search/manipulation function to return an error condition.
$str = string_function(...)
if ( $str === false ) {
#error
} else {
#continue processing $str
}
- ajross 18y agoYeah, but that's a little mixed up, like a lot of PHP. That function returns a string, and something "not a string" to indicate completion. The standard way this is done in sane languages is to declare a nil reference (null pointer, whatever, undefined constant, etc...) that is guaranteed to be distinct from all strings, not to overload a "boolean" on top of a function that returns things that can be implicitly converted to a boolean in the first place. Perl, for example, would write that test as "if(defined $str) {...}". The point being: strings and booleans are an overlapped type space. If you want something outside that space, the proper choice is not a boolean.
- nuclear_eclipse 18y agoWell, if you prefer it that way, there is a 'null' keyword as well that does exactly what you want: $str = string_function(...); if ( is_null( $str ) ) {} if ( null === $str ) {} Just a matter of preference.
- ajross 18y agoTo be clear: it's a matter of correctness, not preference. Using a boolean constant to represent "not a string" when there are legal string values that are equal to that constant is a design bug, that you are working around via the identity operator. I'm happy that PHP has a null; less so that you don't see value in using it where it's required.
- nuclear_eclipse 18y agoWell, my point is: $str = ''; $str == null; #true $str == false; #true null == false; #true So in the case of PHP, it's not a matter of correctness, simply because of how PHP handles type coercion. 'false' and 'null' both have legal string values that can evaluate as equal to them or each other.
- wvenable 18y ago"The point being: strings and booleans are an overlapped type space." That's the problem. Because they overlap for comparisons, you can't tell an empty string apart from boolean false. It would be safer if it wasn't that way. But the function returning false is perfectly valid. It's not any different from returning null or some other value because it is distinct from a string. In PHP, like your Perl example, you could easily write "if (is_bool($str)) {...}" if you wanted to. It's not really any different. The problem is that you don't get an error if you go ahead and treat that boolean as an empty string.