🌐 US-Proxy
class="logged-out env-production page-responsive" style="word-wrap: break-word;" >
Skip to content

Bug: False positive "Cannot call method X() on Y|null" when using nullsafe operator on repeated function calls #15002

Description

@mathieu-noel

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions