Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhpStorm warning PHP variable might not have been defined

Tags:

php

phpstorm

Consider:

<?php
  //  $smith = "";
  $submit ="button_a";

  if($submit == "button_a") {
      $smith = "button_a";
  }
    elseif($submit == "button_b"){
      $smith = "button_b";
  }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>

<body>
    <p>
        <?php echo($smith);  ?>
    </p>
</body>

</html>

PhpStorm provides a flag for each file: Red - Errors, Yellow - Warning, Green - OK.

The PHP code above the header will assign a value to $smith. In the body, I get a warning on $smith saying that it might be undefined. If I declare all of the variable at the top of the PHP code, ($smith = "";) it is happy (no warning).

Is there something that I should be doing to prevent these warnings?

I don't like the idea of attaching the comment to each one saying to not check it and I don't want to turn them all off.

This happens a lot when I include my db_login.php file which defines four or five variables. I have different db_login.php files for WAMP, MAMP, and the real hose.

Any thoughts?

like image 809
mkstlwtz Avatar asked Aug 01 '12 01:08

mkstlwtz


2 Answers

You can tell PhpStorm to ignore undefined variables reports if require on include statements are located in the same execution flow before the variable access.

You'll find it in 'Undefined variable' - Ignore 'include' and 'require' statements. It is enabled by default, so you should disable it.

Enter image description here

*Note: The setting is in menu FileSettings (Ctrl + Alt + S) → Project SettingsInspectionsPHPUndefinedUndefined variable

like image 177
Dreen Avatar answered Oct 23 '22 22:10

Dreen


Yeah, there are two things you can do to get rid of this warning. What you said:

$smith = "";
if($submit == "button_a") {
    $smith = "button_a";
}
elseif($submit == "button_b"){
    $smith = "button_b";
}

Or check if it's set when you print it:

<?php
    if( isset( $smith)) {
        echo($smith);
    }
?>

However, this is just a warning, and it is letting you know that there is a condition that $smith won't be defined (when $submit isn't "button_a" and isn't "button_b"). If that condition were to occur, you would be printing $smith when it wasn't set, which could be a bug in your script.

like image 43
nickb Avatar answered Oct 23 '22 22:10

nickb