psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Mixed type of return value for a static variable that is assigned a specific type

Open cazak opened this issue 1 year ago • 6 comments

This works for a typical variable: https://psalm.dev/r/8c1cff78af

But it doesn't work for a static variable: https://psalm.dev/r/32db7cf425

cazak avatar Jul 29 '23 10:07 cazak

I found these snippets:

https://psalm.dev/r/8c1cff78af
<?php

final class A
{
	public function getB(): B
    {
    	$b = null;
        
        if ($b === null) {
        	$b = new B();
        }
        
        return $b;
    }
}

final class B
{
}
Psalm output (using commit 73ebe22):

No issues!
https://psalm.dev/r/32db7cf425
<?php

final class A
{
	public function getB(): B
    {
    	static $b = null;
        
        if ($b === null) {
        	$b = new B();
        }
        
        return $b;
    }
}

final class B
{
}
Psalm output (using commit 73ebe22):

INFO: MixedReturnStatement - 13:16 - Possibly-mixed return value

INFO: MixedReturnStatement - 13:16 - Could not infer a return type

INFO: MixedInferredReturnType - 5:26 - Could not verify return type 'B' for A::getB

psalm-github-bot[bot] avatar Jul 29 '23 10:07 psalm-github-bot[bot]

Here's a simpler example: https://psalm.dev/r/652f9d7938

MauricioFauth avatar Jan 22 '24 20:01 MauricioFauth

I found these snippets:

https://psalm.dev/r/652f9d7938
<?php

function counter(): int {
    static $i = 0;
    return $i++;
}
Psalm output (using commit 3c90054):

INFO: MixedOperand - 5:12 - Left operand cannot be mixed

INFO: MixedAssignment - 5:12 - Unable to determine the type that $i is being assigned to

INFO: MixedReturnStatement - 5:12 - Could not infer a return type

psalm-github-bot[bot] avatar Jan 22 '24 20:01 psalm-github-bot[bot]

Even simpler, also occurs in global scope.

https://psalm.dev/r/0ec3512e62

discordier avatar Feb 05 '24 14:02 discordier

I found these snippets:

https://psalm.dev/r/0ec3512e62
<?php

static $counter = 0;
$counter++;
Psalm output (using commit 4b2c698):

INFO: MixedOperand - 4:1 - Left operand cannot be mixed

INFO: MixedAssignment - 4:1 - Unable to determine the type that $counter is being assigned to

psalm-github-bot[bot] avatar Feb 05 '24 14:02 psalm-github-bot[bot]

Related: #3101

rzvc avatar Feb 07 '24 05:02 rzvc