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.
switch (isTokenValid(getBearerToken())){
case true:
$offers = getOffers($product, getBearerToken());
break;
default:
requestBearerToken();
$offers = getOffers($product, getBearerToken());
}
Alert:
CodePudding user response:
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.