让PhpStorm意识到继承的Singleton类

时间:2018-03-27 14:35:50

标签: php singleton phpstorm

我在父类

中有以下代码
class parent {
    /**
     * Memory of the instances of the classes.
     * @since  1.0.0
     * @access protected
     * @static
     * @var array
     */
    protected static $instances = [];

    /**
     * Singleton
     * Thanks to: https://stackoverflow.com/a/45500679/8148987
     * @since  1.0.0
     * @access public
     * @static
     * @return object
     */
    public static function instance() {

        if ( empty( self::$instances[static::class] ) ) {
            $instance                       = new static();
            self::$instances[static::class] = $instance;
        } else {
            $instance = self::$instances[static::class];
        }

        return $instance;
    }
}

儿童类

class child extends parent {

    public function test() {

    }

}

我可以使用以下代码:

$class_child = child::instance();

但是PhpStorm并不知道test()方法。

如果我写$class_child->,则不会列出任何提案。我该怎么办?

此处提到的解决方案https://stackoverflow.com/a/32014968/8148987在我的案例中不起作用。

1 个答案:

答案 0 :(得分:1)

@return static方法的PHPDoc中使用@return object代替instance()

现在PHPDoc告诉该方法返回一些对象(可以是任何对象)。

使用@return static,它将返回使用instance()方法的类的实例。因此,对于ChildClass,它将被解释为@return ChildClass,对于GrandChildClass,它将被解释为@return GrandChildClass