简体   繁体   中英

PHPDoc for “casted” return type

I have some kind of factory where a method returns one of multiple possible classes but they all inherit the same parent class. The factory method returns always the same class when it gets the same parameter. So when I receive a class from the factory method I know the subclass beside the common parent class.

The problem is that PhpStorm shows me a warning when I try to set the @return type to the child class.

Here an example:

abstract class Base {}
class A extends Base {}
class B extends Base {}

class T {
    /**
     * @param string $class
     * @return Base
     */
    public function returnBase($class)
    {
        switch ($class) {
            case 'A':
                return new A();
                break;
            // ... more cases ...
            default:
                return new B();
        }
    }
    /**
     * @return A
     */
    public function test()
    {
        return $this->returnBase('A'); // Warning: "Return value is expected to be 'A', 'Base' returned"
    }
}

I know in this example I could set the return type of returnBase() to A|B , but in my actual code I have much more classes. I don't want to set the return type of the test() method to "Base" because the subclass might have unique methods/properties.

You can set a varibale type for each returnBase() method like this :

/**
 * @return A
 */
public function test()
{
    /** @var A $a */
    $a =  $this->returnBase('A');
    return $a;
}

Accroding to this article about PHP's Garbage Collection , a redundant variable doesn't have any impact on memory consumtion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM