A PHP useless assignment to local variable major code smell even when passed by reference (&)

SonarQube: Community Edition, Version 7.9.1 (build 27448)
SonarScanner:
INFO: SonarQube Scanner 4.2.0.1873
INFO: Java 11.0.3 AdoptOpenJDK (64-bit)
INFO: Linux 5.0.0-36-generic amd64

Code sample:

private function sonar() {
        $max = 0;
        $arr = [ 2, 5, 1, 10 ];
        foreach($arr as $item) {
            $f = function($in) use(&$max) {
                if($in > $max) {
                    $max = $in;
                }
            };

            $f($item);
        }
        return $max;
    }

This function works well since the $max variable has been passed by reference. I know nobody would write this function this way that but this is just example.

The code smell is false-positive

Hello @Hell4Ge and welcome in this community!

This is indeed a false positive, which seems to be related to this existing ticket: https://jira.sonarsource.com/browse/SONARPHP-860, although it’s not quite exactly the same case. Anyway, thank you for the reproducer!

There is currently some ongoing work on the SonarPHP analyzer in order to support PHP 7.4 which is about to be released. I can’t promise you anything, but I’ll try to have a look at this FP in order to fix it in the next version of the plugin.

Hope this helps,
Guillaume