Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I be sure this local variable is set after switch statement?

I have a scenario in my code where PhpStorm alerts me that a local variable $offers may be undefined. You can find the code scenario below as well as the alert from the IDE. Is intellisense right or wrong? The local variable is set regardless of the case as far as I can see.

Code:

function checkProduct($product, $retailerId){
    switch (isTokenValid(getBearerToken())){
        case true:
            $offers = getOffers($product, getBearerToken());
            break;
        case false:
            requestBearerToken();
            $offers = getOffers($product, getBearerToken());
            break;
    }
  if(!isBestOfferOurs($offers)){
    alertRetailer($product);
  }
}

EDIT:
replacing the false case to a default seems to resolve the issue and this ensures that $offers is always set.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        case true:
            $offers = getOffers($product, getBearerToken());
            break;
        default:
            requestBearerToken();
            $offers = getOffers($product, getBearerToken());
    }```
Alert:

[![php alert][1]][1]


  [1]: https://i.stack.imgur.com/Y7zVc.png

>Solution :

You can either preset the variable at the beginning of your function to an empty value, or you could add a default case to your switch statement below the false case. Either of those should satisfy your IDE.

Even though PHP switch statements do a loose type comparison (https://www.php.net/manual/en/control-structures.switch.php), PhpStorm doesn’t seem to know that and thinks that there could be a value that isn’t satisfied by your switch statement (which is why I suggested adding a default case). So it’s technically wrong.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading