Search code examples
phpphpstorm

PhpStorm, return value is expected to be 'A', 'object' returned


I have this:

class A {}
class B {}

class X
{
    private function create(string $class) : object
    {
        return new $class();
    }
    
    public function createA() : A
    {
        return $this->create('A');
    }

    public function createB() : B
    {
        return $this->create('B');
    }
}

And as the screenshot says:

enter image description here

What to set for return type to indicate that it is an "object"? Unfortunately A and B don't have anything in common (except that THEY BOTH ARE OBJECTS!!!!)


Solution

  • Has to be because object can be ANY class instance, even B etc.

    You can annotate the create() method with generics PHPDoc to tell that the return type will be the same as the input parameter class string. It gives more context info to the IDE.

        /**
         * @template T
         *
         * @param string $class
         * @return T
         */
        private function create(string $class) : object
        {
            return new $class();
        }
    

    enter image description here

    P.S.

    Instead of create('B'); better use create(B::class). This way the IDE can track the usages of that class for refactoring/search purposes etc.