提问者:小点点

phpstan:如何处理派生类返回类型


对于此示例代码,phpstan生成错误的正确修复方法是什么?错误消息是:

方法Foo::Foo()应返回Child,但返回Base

<?php declare(strict_types = 1);

Interface MyI {abstract function a(): self;}
Class Base implements MyI { 
    public function a(): self {return $this;} 
}
Class Child extends Base { 
    public function c(): self {return $this;} 
}
Class Foo {
public function factory(): Child {return new Child();}
/**
 * @return Child
 */
public function foo() /* note no return type */  {
    return $this->factory()
        ->c()
        ->a();
}

}

消除错误的一种方法是将@return更改为:

/**
 * @return Child | Base
 */

但是我非常不喜欢它,因为foo()从不返回Base的实例。该代码仅适用于派生类子类。事实上,接口和基类都在一个库(依赖项)中,所以我甚至不能更改代码。

我可以在我的子类中重新实现a(),如下所示:

    public function a(): Child {
        parent::a();
        return $this;
    }

但这也很难看,更糟糕的是,这是一个玩具的例子。在实际的类中,我必须重新实现许多方法。非常糟糕。


共1个答案

匿名用户

你需要返回静态https://phpstan.org/r/42ee409c-ada2-44c9-a26d-6a85c2327bca

要了解所有不同的PHPDoc可能性,请前往PHPStan留档:

  • https://phpstan.org/writing-php-code/phpdocs-basics