PHP如果语句不看第二个参数,如果第一个有效
问题描述:
我已经注意到,如果第一个参数为true,PHP不会运行'if语句'的第二个或其他参数。PHP如果语句不看第二个参数,如果第一个有效
if($this->sessions->remove("registered_id") or $this->sessions->remove("user_id")){
echo "you have logged out";
}else {
echo "wth?";
}
这个我怎么用if。此处还有会话类的删除功能。
public function remove($key){
if(isset($_SESSION[$key])){
unset($_SESSION[$key]);
return true;
}
else
{
return false;
}
}
,我想要做的事情是同时运行此参数。我希望我可以告诉这个问题..的
答
您需要执行这两个函数,存储它们各自的结果,然后测试这些结果。
$resultA = $this->sessions->remove("registered_id");
$resultB = $this->sessions->remove("user_id");
if ($resultA or $resultB)
{
…
它的设计在于第二条语句没有执行,因为它的结果是不相关的。
答
如果其他参数你指的是第二个条件,然后使用,而是的OR
如果其他参数表示else,则改为使用单独的if语句。
编辑
如果你想同时执行语句,使用位运算符,看看这个手册: http://www.php.net/manual/en/language.operators.bitwise.php
喜欢的东西:
if(a | b){
}
将执行两a和b,但仍然是'或'比较。
答
该结果是预期的。这是logical operators做的。
您将需要使用&&
或and
实现你仿佛在寻找:
if ($this->sessions->remove("registered_id") && $this->sessions->remove("user_id")) {
这是为什么:
的&&
或and
关键字意味着所有的评估必须返回true。所以:
if ($a && $b) {
// $a and $b must both be true
// if $a is false, the value of $b is not even checked
}
的||
或or
关键字意味着要么评价必须返回true。所以:
if ($a || $b) {
// Either $a or $b must be true
// If $a is false, the parser continues to see if $b might still be true
// If $a is true, $b is not evaluated, as our check is already satisfied
}
你的情况
所以,如果$this->sessions->remove("registered_id")
成功地做到了这一点,该$this->sessions->remove("user_id")
不会被调用,因为我们的检查已经满足第一次调用的结果。
所以你想运行'if'和'else'? – putvande
http://en.wikipedia.org/wiki/Short-circuit_evaluation – Phil
不,我想同时删除registered_id和user_id,而不使用另一个之内的if .. – Yusuf