unexpected cast to boolean?

[亡魂溺海] 提交于 2019-12-22 09:00:00

问题


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?

This block gives the expected values:

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
}

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;
}

回答1:


You should use parentheses:

if(($id=validkey($_GET['supply_id'])) && ($room=validkey($_GET['room']))) 

Otherwise the result of validkey($_GET['supply_id']) && $room=validkey($_GET['room']) is assigned to $id variable because && operator has higher precedence than =




回答2:


The && operator binds stronger than the = operator.

So your code basically becomes if ($id = (validkey($_GET['supply_id']) && $room = validkey($_GET['room'])))

--> Add parenthesis around the $foo = $bar expressions in your IF statement.




回答3:


You seem to have a small error in your second example - a stray doubble quote after $id. Also, your second approach is generally frowned upon (assigning variables in an if construct) as it makes code considerably harder to follow. Clearer would be the following:

if (isset($_GET['supply_id']) && isset($_GET['room'])) {     
    $id=validkey($_GET['supply_id']); //18823     
    $room=validkey($_GET['room']); //248

    if($id && $room) {     
        $arr=array('s'=>$id,'r'=>$room); //s=>18823, r=>248 
    }
} 


来源:https://stackoverflow.com/questions/5091986/unexpected-cast-to-boolean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!