Search code examples
phppsalm-php

How to tell psalm to save getter state if property wasn't modified before the further checks?


class A
{
    private ?string $x = null;

    public function getX(): ?null
    {
        return $this->x;
    }
}

class B
{
    public function __construct(string $y)
    {
        // Property initialization...
    }
}

$a = new A();
if ($a->getX() !== null) {
    $b = new B($a->getX());
}

For this code snippet psalm will return an error like PossiblyNullOperand or similar. I know that this is kind of an expected behavior, and can be fixed like this:

$a = new A();
if (($x = $a->getX()) !== null) {
    $b = new B($x);
}

But is there a configuration parameter in psalm, which will ignore these errors for methods like getters which always return the same result?

Psalm version: 4.18.x


Solution

  • Psalm need to know that the function has a consistent return value.

    This is something you can describe with @psalm-mutation-free: https://psalm.dev/r/e3906e5985