1

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().

5
  • Please post a minimal reproducible example in the question, not at a remote link. Commented Feb 8, 2024 at 23:55
  • Don't know if it will help, but maybe if (in_array("display", get_class_methods($this))) Commented Feb 8, 2024 at 23:59
  • Nope - same behaviour Commented Feb 9, 2024 at 0:07
  • 1
    Handling dynamic conditions is generally difficult in static analyzers. Commented Feb 9, 2024 at 0:09
  • No idea if it will make any difference, but try changing class_implements(static::class) to class_implements($this). Maybe PHPStan doesn't realize that static::class and $this are interchangeable in that context (since you check static::class but are using $this->display() after). I've seen similar "false-positive-errors" in IDE's. Commented Feb 9, 2024 at 1:32

1 Answer 1

1

Ask $this instanceof Displayable.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.