I am told that good developers can spot/utilize the difference between Null
and False
and 0
and all the other good "nothing" entities.
What is the difference, specifically in PHP? Does it have something to do with ===
?
Null
means "nothing". The var has not been initialized.
False
means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.
0
is an int
. Nothing to do with the rest above, used for mathematics.
Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context, which (in PHP) is False
.
If you test it with ==
, it's testing the boolean value, so you will get equality. If you test it with ===
, it will test the type, and you will get inequality.
Well, look at the strrpos()
function. It returns False if it did not find anything, but 0 if it has found something at the beginning of the string!
<?php
// pitfall :
if (strrpos("Hello World", "Hello")) {
// never exectuted
}
// smart move :
if (strrpos("Hello World", "Hello") !== False) {
// that works !
}
?>
And of course, if you deal with states, you want to make a difference between the following:
DebugMode = False
(set to off)DebugMode = True
(set to on)DebugMode = Null
(not set at all; will lead to hard debugging ;-))