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

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

PHP宽松的类型系统提供了许多不一样的方法来检测一个变量的值。然而这也形成了不少问题。 使用==来检测一个值是否为null或false,若是该值其实是一个空字符串或0,也会误报 为false。isset是检测一个变量是否有值, 而不是检测该值是否为null或false,所以在这里使用是不恰当的。php

is_null()函数能准确地检测一个值 是否为null,is_bool能够检测一个值 是不是布尔值(好比false),但存在一个更好的选择:===操做符。===检测两个值是否同一, 这不一样于PHP宽松类型世界里的相等。它也比is_null()和is_bool()要快一些,而且有些人 认为这比使用函数来作比较更干净些。ide

示例函数

<?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(),始终使用===!==,不然 你就会碰到问题。