问题
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;
}
}
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.
回答1:
If you have switch
cases that are the same, you can combine them by omitting the return
and break
lines of the earlier cases.
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;
}
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;
}
Hope this helps! :)
回答2:
Ternary operator - all in one line:
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);
return $userRow['user_role']<3 && $userRow['user_role']>7 ? false : true;
}
回答3:
You could use in_array like this:
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'];
return in_array($role, [
3,
4,
5,
6,
7
], true);
}
回答4:
A lookup array can be used to eliminate condition statements.
Because in_array()
is much slower than isset()
it is advisable to set up your lookup are to store values as keys.
Code:
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);
$lookup=[3=>'',4=>'',5=>'',6=>'',7=>'']; // or array_flip(range(3,7))
return isset($lookup[$userRow['user_role']]);
}
This solution becomes even more useful when your identifying values are non-sequential -- you just list them in an array: $lookup=[3=>'',6=>'',9=>''];
This approach is very easy to maintain as your requirements grow/change.
Lastly, you don't need to write break
after a return
because the return
halts all actions inside the function.
来源:https://stackoverflow.com/questions/47784526/how-eliminate-duplicate-cases-from-a-switch-statement-in-php