In PHP I’d like to do this:
switch (function_foo($bar,$bar2)) {
case $fu:
*Do Stuff*
break;
case $fubar:
*Do Other Stuff*
break;
}
Is this a terrible idea? Will it work?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using a function in the
switchis OK : the function will be called, and will return a value — which is the one that will be used for the case.It’s exactly the same as writing :
Even if I prefer using a variable, so the code is easier to read.
And using variables in the `case` is something you don’t see often ; but it works fine too 😉
Quoting the manual page of
switch:So, your code will work, as long as
$fuand$fubarcontain simple-type values.Using a variable as a `case` value not often done *(as far as I can tell from the code I read)*, probably because some other languages don’t allow that *(for instance, C doesn’t allow that ; and the `switch`/`case` structure is borrowed from C)* ; but it works :
Will output :