0

I got the following problem with PHPStan :

<?php declare(strict_types = 1);

class Player {
    public int $userID = 2;
}

class Scope
{
    private function __construct(
        public readonly ?Player $player,
    ) {
    }

    public function isPlayer(): bool
    {
        return $this->player !== null;
    }

    public function getUserID(): int
    {

        if ($this->isPlayer()) {
            return $this->player->userID;
        }
        
        throw new \RuntimeException('empty');
    }
    
    public function getUserIDOK(): int
    {
        if ($this->player !== null) {
            return $this->player->userID;
        }
        
        throw new \RuntimeException('empty');
    }
}

See : https://phpstan.org/r/0f74630c-0a67-49dc-bfae-c559ac5aab4d

I don't understand why PHPStan triggers a 23 | Cannot access property $userID on Player|null. error for the getUserID() method which is basically doing the very same thing as the getUserIDOK() method.

Would appreciate any help,

Cheers

ERO
  • 55
  • 4
  • I fairly certain that PHPStan is only evaluating the signature of the method you are calling, not what it is actually doing, and as such it does not see that a null check was also performed. If someone were to change the contents of `isPlayer()`, possibly including a database connection that PHPStan can't analyze, you'd be happy to have caught it here. – Chris Haas Jan 24 '23 at 17:23

0 Answers0