PHP 寬松的類型系統(tǒng)提供了許多不同的方法來檢測一個變量的值。 然而這也造成了很多問題。 使用 == 來檢測一個值是否為 null 或 false,如果該值實際上是一個空字符串或 0,也會誤報為 false。 isset 是檢測一個變量是否有值, 而不是檢測該值是否為 null 或 false,因此在這里使用是不恰當?shù)摹?/p>
is_null() 函數(shù)能準確地檢測一個值是否為 null, is_bool 可以檢測一個值是否是布爾值(比如 false), 但存在一個更好的選擇:=== 操作符。=== 檢測兩個值是否同一, 這不同于 PHP 寬松類型世界里的 相等。它也比 is_null() 和 is_bool() 要快一些,并且有些人認為這比使用函數(shù)來做比較更干凈些。
<?php
$x = 0;
$y = null;
// Is $x null?
if($x == null)
print('Oops! $x is 0, not null!');
// Is $y null?
if(is_null($y))
print('Great, but could be faster.');
if($y === null)
print('Perfect!');
// Does the string abc contain the character a?
if(strpos('abc', 'a'))
// GOTCHA! strpos returns 0, indicating it wishes to return the position of the first character.
// But PHP interpretes 0 as false, so we never reach this print statement!
print('Found it!');
//Solution: use !== (the opposite of ===) to see if strpos() returns 0, or boolean false.
if(strpos('abc', 'a') !== false)
print('Found it for real this time!');
?>