如何从 PHP 中的 switch 语句中消除重复的情况 [英] How eliminate duplicate cases from a switch statement in PHP

查看:38
本文介绍了如何从 PHP 中的 switch 语句中消除重复的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个函数来返回给定的 user_id 是否是网站的工作人员.这就是我所拥有的并且它有效,但是我觉得它可以大大改进.

I'm making a function to return whether or not the given user_id is a staff member of the site. This is what I have and it works, however I feel like it can be greatly improved.

public function isUserStaff($uid) {
    $stmt = $this->conn->prepare("SELECT user_role FROM users WHERE user_id=:user_id");
    $stmt->execute(array(':user_id'=>$uid));
    $userRow = $stmt->fetch(PDO::FETCH_ASSOC);

    $role = $userRow['user_role'];

    switch($role) {
        case 3:
            return true;
            break;
        case 4:
            return true;
            break;
        case 5:
            return true;
            break;
        case 6:
            return true;
            break;
        case 7:
            return true;
            break;
        default:
            return false;
            break;
    }
}

我希望有人能帮助我并描述如何改进我的代码.我认为 case 太多了,我正在寻找更小的东西来使用.

I hope someone can help me out and describe how I can make my code better. I think there are too many case's and I'm looking for something smaller to use.

推荐答案

如果你有相同的 switch 案例,你可以通过省略 returnbreak 行之前的情况.

If you have switch cases that are the same, you can combine them by omitting the return and break lines of the earlier cases.

下面的3456都取return case 7 (true) 的值:

In the following, 3, 4, 5 and 6 all take the return value of case 7 (true):

switch($role) {
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
        return true;
        break;
    default:
        return false;
        break;
}

尽管如此,考虑到 一切 似乎与默认值不同,返回的方式相同,您最好使用简单的 if 条件.您甚至可以指定角色应该在 3 到 7 之间:

Although having said that, considering everything seems to return the same way apart from your default, you might be better off making use of a simple if condition. You can even specify that the roles should be between 3 and 7:

if ($role >= 3 && $role <= 7) {
    return true;
}
else {
    return false;
}

希望这有帮助!:)

这篇关于如何从 PHP 中的 switch 语句中消除重复的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆