Does variables' order matter when doing == and === comparisons?
This question already has an answer here:
It prevents typos which cause very hard to debug bugs. That's in case you accidentally write =
instead of ==
:
if ($var == null) # This is true in case $var actually is null
if ($var = null) # This will always be true, it will assign $var the value null
Instead, switching them is safer:
if (null == $var) # True if $var is null
if (null = $var) # This will raise compiler (or parser) error, and will stop execution.
Stopping execution on a specific line with this problem will make it very easy to debug. The other way around is quite harder, since you may find yourself entering if
conditions, and losing variable's values, and you won't find it easily.
I think that the following code will explain it:
echo (( 0 == NULL ) ? "0 is null" : "0 is not null") ."n";
echo (0 === NULL) ? "0 is null" : "0 is not null" ;
it will output:
0 is null
0 is not null
The ===
operator checks for both value and type, but 0 is a number while NULL is of type NULL
The ==
operator checks only for value and zero can be casted to "false" or "null" hence the "truthy" that we get for the first line
Compare results from this to if
s.
echo "Test '1abc' == 1 - ";
if ('1abc' == 1) {
echo 'ok';
} else {
echo 'fail';
}
echo "nTest '1abc' === 1 - ";
if ('1abc' === 1) {
echo 'ok';
} else {
echo 'fail';
}
Then read this page http://php.net/manual/en/language.types.type-juggling.php it's very interesting lecture ;)
链接地址: http://www.djcxy.com/p/58460.html上一篇: PHP检查用户是否是Admin