使用===操作符來檢測null和布爾false值。
PHP寬鬆的類型系統提供了許多不同的方法來檢測一個變數的值。然而這也造成了很多問題。 使用==來檢測一個值是否為null或false,如果該值實際上是一個Null 字元串或0,也會誤判 為false。isset是檢測一個變數是否有值, 而不是檢測該值是否為null或false,因此在這裡使用是不恰當的。
is_null()函數能準確地檢測一個值 是否為null,is_bool可以檢測一個值 是否是布爾值(比如false),但存在一個更好的選擇:===操作符。===檢測兩個值是否同一, 這不同於PHP寬鬆類型世界裡的相等。它也比is_null()和is_bool()要快一些,並且有些人 認為這比使用函數來做比較更乾淨些。
樣本
<?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!');?>
陷阱 測試一個返回0或布爾false的函數的傳回值時,如strpos(),始終使用===和!==,否則 你就會碰到問題。