Bug report
When calling a function that returns a nullable object type (?Acme) twice and using the nullsafe operator (?->) on each call, the analyzer incorrectly reports an error, even though each call is individually guarded by ?->.
<?php declare(strict_types = 1);
class Acme {
public function foo(): int {
return 1;
}
}
function getAcme(bool $enabled = true): ?Acme {
return $enabled ? new Acme() : null;
}
$bar = getAcme()?->foo();
$baz = getAcme()?->foo();
Code snippet that reproduces the problem
https://phpstan.org/r/2c6f2c68-6f08-4f53-9082-aa2e86849b0b
Expected output
No error should be raised, since the nullsafe operator (?->) already guards against calling foo() on null.
Workaround
Assigning the result of the function call to an intermediate variable before using the nullsafe operator avoids the false positive:
$acme = getAcme();
$bar = $acme?->foo();
$baz = $acme?->foo();
Environment
- PHP version: 8.5
- Tool version: 2.2.5
- Level: max
Additional notes
The issue seems related to how the analyzer tracks the return type of repeated identical expressions (getAcme()), rather than an actual issue with the nullsafe operator itself.
Did PHPStan help you today? Did it make you happy in any way?
No response
Bug report
When calling a function that returns a nullable object type (
?Acme) twice and using the nullsafe operator (?->) on each call, the analyzer incorrectly reports an error, even though each call is individually guarded by?->.Code snippet that reproduces the problem
https://phpstan.org/r/2c6f2c68-6f08-4f53-9082-aa2e86849b0b
Expected output
No error should be raised, since the nullsafe operator (
?->) already guards against callingfoo()onnull.Workaround
Assigning the result of the function call to an intermediate variable before using the nullsafe operator avoids the false positive:
Environment
Additional notes
The issue seems related to how the analyzer tracks the return type of repeated identical expressions (
getAcme()), rather than an actual issue with the nullsafe operator itself.Did PHPStan help you today? Did it make you happy in any way?
No response