意外转换为布尔值? [英] unexpected cast to boolean?
问题描述
输入以下内容: http://example.com/item.php? room = 248& supply_id = 18823 ,以下2个块应该产生相同的结果.他们为什么不呢?除了咖啡,我还想念什么?
Given this input: http://example.com/item.php?room=248&supply_id=18823, the following 2 blocks ought to produce the same result. Why don't they? What am I missing other than coffee?
此块给出了期望值:
if (isset($_GET['supply_id']) && isset($_GET['room'])) {
$id=validkey($_GET['supply_id']); //18823
$room=validkey($_GET['room']); //248
$arr=array('s'=>$id,'r'=>$room); //s=>18823, r=>248
}
但是如果我一步完成检查和赋值,$ id最终等于1而不是18823.为什么?
But if I do the check and the assignment in one step, $id ends up equal to 1 instead of 18823. Why?
if (isset($_GET['supply_id']) && isset($_GET['room'])) {
if($id=validkey($_GET['supply_id']) && $room=validkey($_GET['room']))
$arr=array('s'=>$id",'r'=>$room); //s=>1, r=>248
}
这是我正在使用的功能:
This is the function I'm using:
function validkey($value){
if(is_scalar($value)){
$value=(int)$value;
return ($value>0) ? $value : false;
}
return false;
}
推荐答案
您应该使用括号:
if(($id=validkey($_GET['supply_id'])) && ($room=validkey($_GET['room'])))
否则,将validkey($_GET['supply_id']) && $room=validkey($_GET['room'])
的结果分配给$id
变量,因为&&
运算符的优先级高于=
Otherwise the result of validkey($_GET['supply_id']) && $room=validkey($_GET['room'])
is assigned to $id
variable because &&
operator has higher precedence than =
这篇关于意外转换为布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!