企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 使用 [===](http://php.net/manual/zh/language.operators.comparison.php) 操作符来检测 null 和布尔 false 值。 PHP 宽松的类型系统提供了许多不同的方法来检测一个变量的值。 然而这也造成了很多问题。 使用 `==` 来检测一个值是否为 null 或 false,如果该值实际上是一个空字符串或 0,也会误报为 false。 [isset](http://php.net/manual/zh/function.isset.php) 是检测一个变量是否有值, 而不是检测该值是否为 null 或 false,因此在这里使用是不恰当的。 [is_null()](http://php.net/manual/zh/function.is-null.php) 函数能准确地检测一个值是否为 null, [is_bool](http://php.net/manual/zh/function.is-bool.php) 可以检测一个值是否是布尔值(比如 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(),始终使用 `===` 和`!==`,否则你就会碰到问题。 ## 进一步阅读 * [PHP 手册:比较操作符](http://php.net/manual/zh/language.operators.comparison.php) * [Stack Overflow: is_null() vs ===](http://stackoverflow.com/questions/8228837/is-nullx-vs-x-null-in-php) * [Laruence:isset 和 is_null 的不同](http://www.laruence.com/2009/12/09/1180.html)