Catch possibly uninitialized variables in PHP

Versions:

  • SonarQube 8.9.6
  • Scanner 4.2.0

A bug got through scanning that I thought would be caught. It seems as though this rule: PHP static code analysis: Variables should be initialized before use only checks if a variable is definitely undefined before it’s used. Is there a rule that cheks if a variable could be undefined before it’s used? Something like the Psalm “Possibly Undefined Variable” ?

Hi @joaquimds,

Welcome to the community. Can you provide some code examples for a better understanding?

Best,
Nils

Hi Nils,

Thank you for your reply. Here is some sample code:

<?php

// Will fail Qube
function bad() {
    $cond = true;
    if ($cond) {
        $text .= "test";
    }
    echo $text . "\n";
}
bad();

// Will not fail Qube
function alsoBad() {
    $cond = false;
    if ($cond) {
        $text = "";
    }
    $text .= "test";
    echo $text . "\n";
}
alsoBad();

Hi @joaquimds,

thank you for the reproducer and sorry for the late response. Currently, this is due to our missing support for path sensitivity. I’ve created a ticket which will be addressed when we enable path sensitivity for PHP.

Thanks again for your contribution.

Best,

Thank you!