缘起
今天写 API 接口, 碰到一个由 empty() 引起的坑.
背景
功能要求: 根据 GET 传参, 更新数据表字段;
该参数的取值范围: 0, 1, 2;
思路: 通过 $_GET['var'] 获取参数值, 然后拼接 SQL 语句;
第 1 次尝试
在使用 $_GET['var'] 获取参数值时, 很自然地想到使用 if(!empty($status)) 判断参数值是否存在, 以决定是否拼接 SQL 语句:
$sql_condition = ' AND id = :id';
$status = $_GET['status'];
if(!empty($status)){
$sql_condition .= ' AND status = :status';
}
测试时发现: 当 status == 0 时, !empty($status) 为 false, 导致直接略过了
SQL 语句拼接.
查阅手册, 得知 empty() 的功能是判断"是否为空或者是否被认为false":
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE
而在 PHP 中, 下列情况被认为是 false:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0" (空字符串, 和值为0的字符串!)
an array with zero elements (空数组)
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables / 包括已经销毁的变量)
SimpleXML objects created from empty tags
也就是说, 当 $status == 0 时, empty($status) 实际上被计算机理解成empty(false), 结果是 true, 所以取反后, !empty(false) 为 false
既然 empty() 不能有效地处理数字 0, 那么想到使用 isset() 函数来判断 -- 所以进行了下面的第 2 次尝试.
第 2 次尝试
$sql_condition = ' AND id = :id';
$status = $_GET['status'];
if(isset($status)){
$sql_condition .= ' AND status = :status';
}
测试时发现解决了 status == 0 的情况, 但是当 status == '' (即 status 为空数组)时, isset($status) 为 true, 导致 SQL 语句的拼接, 从而导致数据库的错误写入!
查阅手册得知: 当 $var 为空数组时, isset($var) 为真.
这时候感觉思路有点绕晕了.
上网查询, 发现有人总结了一张对比表格, 能够很直观地观察 empty() 和
isset() 的差异:
/
gettype()
empty()
is_null()
isset()
(bool)
$x = "";
string
true
false
true
false
$x = null;
NULL
true
true
false
false
var $x; (not set)
NULL
true
true
false
false
$x = array();
array
true
false
true
false
$x = false;
boolean
true
false
true
false
$x = 15;
integer
false
false
true
true
$x = 1;
integer
false
false
true
true
$x = 0;
integer
true
false
true
false
$x = -1;
integer
false
false
true
true
$x = "15";
string
false
false
true
true
$x = "1";
string
false
false
true
true
$x = "0";
string
true
false
true
false
$x = "-1";
string
false
false
true
true
$x = "foo";
string
false
false
true
true
$x = "true";
string
false
false
true
true
$x = "false";
string
false
false
true
true
区分清楚这些概念后, 重新整理思路:
我想达到的效果是:
能够在参数值为空时, 逻辑判断为 false, 跳过 SQL 语句拼接;
当参数值为 0 时, 逻辑判断为真, 进行 SQL 语句拼接.
根据上面的表格, empty() 显然无法满足我的 2 个特殊要求, 而 isset() 只能满足"参数值为 0"的情况;
找不到直接的函数来满足需求, 那么尝试使用"或且非"的逻辑条件来丰富判断条件. 最终选定的判断条件是 if(isset($status) && $status != ''), 见下面的第 3 次尝试.
第 3 次尝试
$sql_condition = ' AND id = :id';
$status = $_GET['status'];
if(isset($status) && $status != ''){
$sql_condition .= ' AND status = :status';
}
测试后, 确认满足需求.
只是代码有些丑陋, 对于这个解决方法有些没底气(囧), 查找 StackOverflow, 发现有类似的回答:
if ( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
...
}
从而确信自己的解决方案是合理的, Bingo! ^_^
另外的解决方案
对于我这种情况, 直接 is_int() 就满足要求了:
$sql_condition = ' AND id = :id';
$status = $_GET['status'];
if(is_int($status){
$sql_condition .= ' AND status = :status';
}
文章历史
2016/12/20 (第一次发布)
2018/01/31 (添加 is_int() 的解决方案; 润色)
如果你觉得我的文章对你有用, 请打个"喜欢", 或者给些改进的建议 _