0

我在 cakePHP 应用程序中有一个 if 语句,但我无法弄清楚为什么它没有达到我的预期。

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

我希望如果有一个具有“代理”角色的用户,它将拒绝所有操作。

如果我使用它而不是一切都是玫瑰色的,只是不确定为什么在将布尔值设置为 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;
    }

有任何想法吗?谢谢

4

1 回答 1

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'))){

}
于 2012-11-23T23:28:37.197 回答