Skip to content

Value incorrectly inferred as falsy, weird interference with other variables #7937

@sylbru

Description

@sylbru

Bug report

Hi! Tried this on the playground with bleeding edge, so I guess it’s the latest version.
I have an int incorrectly inferred as the value 0, hence giving me a "Negated boolean expression is always true" error.
The weird thing is the three blocks that come before the nested ifs in the example below:

  • try removing the first one (if + return) and the error disappears, even though the block being there doesn’t tell us anything about $a and $b independently (just that at least one of them must be truthy);
  • try removing the space in string literal in $output = " "; and the error disappears;
  • try removing the next block (if ($a) …) and the error disappears. Or you can replace the string value by any string literal (without interpolation) other than the empty string, it also "works."

Code snippet that reproduces the problem

https://phpstan.org/r/ee1dace3-b155-46ca-a2d3-23b2a164f1fe

public function f(int $a, int $b)
{
    if (!$a && !$b) {
        return "";
    }
	
    $output = " ";
    
    if ($a) {
        $output .= "$a";
    }
    
    \PHPStan\dumpType($a);
	
    if ($b) {
        \PHPStan\dumpType($a);
		
        if (!$a) {
            $output .= "_";
        }
    }
    
    return $output;
}

Expected output

$a should still be inferred as int, and not trigger a "Negated boolean expression is always true" error in the last if.

Did PHPStan help you today? Did it make you happy in any way?

I’ve been spending the day fixing errors to make my legacy app pass level 5, looking forward to it! :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions