Search code examples
phpphpstorm

PHP Coding Techniques, Is it Necessary/Proper Coding Technique to create variables prior to using them


I've been trying out PhpStorm and it seems like a good IDE. I've noticed that I get these warning on the side of the code window telling me that a variable may not have been defined.

Basic Example

if (some logic here) {

    $getStatus_SQL = 'SELECT status_ID, status_Name FROM myTable';
    $getStatus_RS = $db_con->query($getStatus_SQL);
    $statusOption = ''; <----------- Variable Defined Here -------------<

    while ($status = $getStatus_RS->fetch_assoc()){
        $statusName = $status['status_Name'];
        if ($statusName == $taskStatus){
            $statusOption .= '<option selected value="'.$status['status_ID'].'">'.$status['status_Name'].'</option>';
        } else {
            $statusOption .= '<option value="'.$status['status_ID'].'">'.$status['status_Name'].'</option>';
        }
    }
}

Now I echo $statusOption variable in HTML, and this is where I get the warning saying:

Variable $statusOption may have not been defined

However if I define the variable outside the "If statement" the warning goes away.

Example

$statusOption = NULL;

if (some logic here) {

    $getStatus_SQL = 'SELECT status_ID, status_Name FROM myTable';
    $getStatus_RS = $db_con->query($getStatus_SQL);

    while ($status = $getStatus_RS->fetch_assoc()){
        $statusName = $status['status_Name'];
        if ($statusName == $taskStatus){
            $statusOption .= '<option selected value="'.$status['status_ID'].'">'.$status['status_Name'].'</option>';
        } else {
            $statusOption .= '<option value="'.$status['status_ID'].'">'.$status['status_Name'].'</option>';
        }
    }
}

So my Question is

Is it proper coding technique to define variable before you use them in if or while statements?


Solution

  • In PHP, it is not necessary to define variables or object properties before you use them. Use of an undefined variable will imply a value of null. This will result in a E_NOTICE level log message, or if you are trying to request a method on an undefined object it will be E_ERROR and execution will stop.

    However, it is very good practice to ensure variables are always defined in your code. In PHP, this means not first assigning them inside of conditional statements and, declaring object properties in the class definition.

    The reason for this is that it ensures the variable is always set to a controlled value. Future edits to the code will be easier when the original programmers intentions are clearly defined in the code and are less likely to result in unexpected behavior. If for example, another variable with the same name is declared or the condition that sets the variable is removed. In worst cases, lack of declaring variables could represent a security risk.