Search code examples
phpphpstan

PHP: Phpstan class_implements call interface method: Call to an undefined method


I have a method in an abstract parent class. The behaviour basically depends on wether the child class inherits an interface or not.

How can I make phpstan recognize this conditional (in this case "class_implements")

<?php declare(strict_types = 1);

interface Displayable {
    public function display(): string;  
}

abstract class ParentClass
{
    public function run(): string {
        if (in_array(Displayable::class, class_implements(static::class))) {
            return $this->display();
        }

        return '';
    }
}

class ChildClass extends ParentClass implements Displayable {

    public function display(): string {
        return 'dis';
    }
}

phpstan produces the error:

Call to an undefined method ParentClass::display().


Solution

  • Ask $this instanceof Displayable.

    See supported ways of narrowing types: https://phpstan.org/writing-php-code/narrowing-types