Search code examples
phpstorm

Ignore "Variable might have not been defined" in specific place


I have code like this

<?php
$first_condition = time() % 2 == 0;
$second_condition = time() % 3 == 0;

if ($first_condition) {
    if ($second_condition) {
        $param1 = 'param1_1_1';
    } else {
        $param1 = 'param1_2_1';
        $param2 = 'param2_2_1';
    }
} else {
    if ($second_condition) {
        $param1 = 'param1_1_2';
    } else {
        $param1 = 'param1_2_2';
        $param2 = 'param2_2_2';
    }
}

if ($second_condition) {
    $param2 = $param1;
}

$total = array(
    'param1' => $param2,
    'param2' => $param1,
);

I really know that $param2 would be defined anyway, but PhpStorm say that it's wrong.

enter image description here

Is exist there any way to mark this place as ignored of this inspection? Only this place, not global settings, and only this inspection, not all.


Solution

  • Sure -- you can suppress such warning for that statement.

    Standard procedure:

    1. Place caret on such error/warning.
    2. Invoke Alt + Enter to bring quick fix menu (or via light bulb icon).
    3. Find the right inspection.
    4. Expand submenu (e.g. Arrow Right using keyboard or using mouse -- note: click area can be quite small -- depends on GUI theme used).
    5. Choose Suppress for statement option.

    The above will add special PHPDoc-like comment (/** @noinspection PhpUndefinedVariableInspection */) just before that statement -- it tells IDE to ignore that particular issue here.

    https://www.jetbrains.com/help/phpstorm/suppressing-inspections.html?search=suppress


    On another hand (especially if it's your code/code that you cane edit): why not go a bit safer route and just declare those $paramX variables with default values (e.g. empty string) before the conditionals ... so the variable will be indeed defined? This will prevent such false complains from IDE (when it tries to statically analyse such rather complex logic).


    New subquestion: is it possible to disable inspection only for param1 but not for param2 using /** @noinspection PhpUndefinedVariableInspection */ ?

    Yes and No.

    • Without making changes to the code -- No. Those variables are both used in one statement (array definition) and suppression comment is applied to the whole statement.

    • Yes -- split it into 2 statements if you need such separate suppression.