is there any way to simplify this code to avoid the need for an if to skip to the switch's default value?
I have a configuration table for different authentication methods for a http request, with an option not to set the value to default to a plain http request:
if(!isset($type)) {
$type = "default";
}
switch ($type) {
case "oauth":
#instantinate an oauth class here
break;
case "http":
#instantinate http auth class here
break;
default:
#do an unprotected http request
break;
}
I have no issue with the functionality, but I would like a cleaner solution to switch on an optional variable, is there any way to achieve that? Thanks!
You don't need to set the variable to "default". The default-case will be executed if the variable is not set or has any different value from all other defined cases. But remember: if the variable is not set and you use it in the switch, you will get a notice "Notice: Undefined variable". So if you don't want to disable notices you have to do the check if the variable is set.
Just
switch ($type??'') {
case "oauth":
#instantinate an oauth class here
break;
case "http":
#instantinate http auth class here
break;
default:
#do an unprotected http request
break;
}
is enough on php >= 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With