php最佳实践----检测一个值是否为null或false

使用===操作符来检测null和布尔false值。

PHP宽松的类型系统提供了许多不同的方法来检测一个变量的值。然而这也造成了很多问题。 使用==来检测一个值是否为null或false,如果该值实际上是一个空字符串或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(),始终使用===!==,否则 你就会碰到问题。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值