2012-11-23 93 views
0

我有一个if语句在cakePHP应用程序,我无法弄清楚为什么它没有做我期望的。如果声明不输出预期结果

public function isAuthorized($user) {   
     if ($user['role'] === 'admin'){ 
      return true; 
     } 
     if ((in_array($this->action, array('view', 'index')))&&($user['role'] === 'senior' || 'junior')) { 

      return true; 
     } 
     return false; 
     } 

我想如果有一个用户与角色“代理”它会拒绝所有的行动。

如果我使用这个,而不是everthing玫瑰色,只是不知道为什么它没有检查两个参数之前将布尔值设置为True?

public function isAuthorized($user) { 
     if ($user['role'] === 'admin'){ 
      return true; 
     } 
     if ($user['role'] == 'agent'){ 
      return false; 
     } 
     if (in_array($this->action, array('edit', 'add', 'delete'))) { 
      if ($user['role'] == 'senior' || 'junior') { 
       return false; 
      } 

     } 
     return true; 
    } 

任何想法? 谢谢

回答

2

你的一个测试是错误的,总是评估为真。

if($user['role'] === 'senior' || 'junior'){ 
    //will always be true 
} 

,因为你正在评估'junior'作为一个布尔值,这是真的在PHP。

你的条件应该是:

if($user['role'] == 'senior' || $user['role'] == 'junior'){ 
    ... 
} 

注意,你也可以写这样的:

if(in_array($user['role'], array('senior', 'junior'))){ 

}