phpstan: `/** @return static */` doesn't work properly with extended abstract class

Bug report

PHP Version: 7.4

Somehow /** @return static */ doesn’t work properly in provided code snippet with extra abstract class. However it works in simpler use-case like https://phpstan.org/r/18000821-8803-43f6-b17b-abd1d49c6cce

Code snippet that reproduces the problem

https://phpstan.org/r/771ab3d4-54fb-4552-8c4e-9ac0633e457c

<?php

declare(strict_types=1);

abstract class ClassC
{
    private string $value;
    
    private function __construct(string $value)
    {
        $this->value = $value;
    }
    
    /** @return static */
    public static function fromString(string $value): self
    {
        return new static($value);
    }
}

final class ClassB extends ClassC
{
}

final class ClassA
{
    public function classB(): ClassB
    {
        return ClassB::fromString("any");
    }
}

Expected output

ClassB::fromString(“any”) should not generate an error “Unsafe usage of new static().”

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 17 (13 by maintainers)

Most upvoted comments

Yeah, the implicit PHPDoc inheritance should probably work in this case. Until it’s fixed, please use the explicit /** @return static */ in ClassC as well.