2014-01-23 64 views
0

我已经注意到,如果第一个参数为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; 
     } 
    } 

,我想要做的事情是同时运行此参数。我希望我可以告诉这个问题..的

+0

所以你想运行'if'和'else'? – putvande

+0

http://en.wikipedia.org/wiki/Short-circuit_evaluation – Phil

+0

不,我想同时删除registered_id和user_id,而不使用另一个之内的if .. – Yusuf

回答

4

您需要执行这两个函数,存储它们各自的结果,然后测试这些结果。

$resultA = $this->sessions->remove("registered_id"); 
$resultB = $this->sessions->remove("user_id"); 

if ($resultA or $resultB) 
{ 
    … 

它的设计在于第二条语句没有执行,因为它的结果是不相关的。

2

如果其他参数你指的是第二个条件,然后使用,而是的OR

如果其他参数表示else,则改为使用单独的if语句。

编辑

如果你想同时执行语句,使用位运算符,看看这个手​​册: http://www.php.net/manual/en/language.operators.bitwise.php

喜欢的东西:

if(a | b){ 

} 

将执行两a和b,但仍然是'或'比较。

+0

但它的registered_id可能为空。然后我需要使用或..你不明白我在说什么.. – Yusuf

+0

好吧,对不起,我不明白你最初想做什么。我已经编辑了这篇文章,希望你在找什么。 (按位独占或) – Coderchu

+0

使用按位运算符来防止短路基本上只是在稍后让自己感到迷惑。 :P如果你想评估这两个表达式,那么简单地将它们分别写成单独的语句。 – cHao

1

该结果是预期的。这是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")不会被调用,因为我们的检查已经满足第一次调用的结果。

相关问题