Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP switch - default if the variable is not set

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!

like image 256
kachnitel Avatar asked Mar 22 '23 07:03

kachnitel


2 Answers

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.

like image 133
edditor Avatar answered Mar 31 '23 20:03

edditor


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

like image 23
unxed Avatar answered Mar 31 '23 20:03

unxed