Search code examples
phpswitch-statementisset

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!


Solution

  • 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