Why can't I use a switch like this?
I'm learning OOP PHP. I've got a couple years experience with procedural, but want to take it to the next level.
Anyway, In my mindset of clean neat code, trying out some of the stuff I've learned about OOP, I tried something with a normal PHP Switch statement which I've never tried before, In my mind, it's very logical for it to work like this, but it's not working开发者_开发知识库.
switch(strtoupper($type)) {
case "DELETE" || "UPDATE":
$result['info'] = mysql_affected_rows($this->con);
break;
case "INSERT":
$result['info'] = "Insert Successful";
break;
case "SELECT":
$result['info'] = mysql_num_rows($res);
$result['data'] = mysql_fetch_array($res);
break;
}
What happens is, the first case, the one with the "or" in it is the one that's matched, regardless of if $type contains "SELECT". It seems rubbish that I've got to duplicate that first case if I've got 8 things that all differ in outcome, but 2 things that have the same outcome, why can't I use switch like this?
Thanks.
Use:
switch(strtoupper($type)) {
case "DELETE":
case "UPDATE":
$result['info'] = mysql_affected_rows($this->con);
break;
case "INSERT":
$result['info'] = "Insert Successful";
break;
case "SELECT":
$result['info'] = mysql_num_rows($res);
$result['data'] = mysql_fetch_array($res);
break;
}
There is no "or" for switch, you have to list each case separately.
You should use:
case "DELETE":
case "UPDATE":
$result['info'] = mysql_affected_rows($this->con);
break;
why can't I use switch like this?
Simply because it doesn't work that way. "DELETE" || "UPDATE"
is an expression saying "string OR string", which will always evaluate to boolean true
.
Use the notation shown by @Danae and @Andrej L to work around it.
Like this:
switch (strtoupper($type)) {
case "DELETE":
case "UPDATE":
$result['info'] = mysql_affected_rows($this->con);
break;
}
精彩评论