简体   繁体   中英

Make PhpStorm Aware of inherited Singleton Classes

I have following code in the Parent Class :

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;
    }
}

The Child Class :

class child extends parent {

    public function test() {

    }

}

I can do following with this code:

$class_child = child::instance();

But PhpStorm is not aware of the test() method.

If I write $class_child-> no proposals are listed. What can I do?

The solution mentioned here https://stackoverflow.com/a/32014968/8148987 will not work in my case.

Use @return static instead of @return object in PHPDoc for instance() method.

Right now PHPDoc tells that this method returns some object (can be any object).

With @return static it will return instance of a class where that instance() method was used. So for ChildClass it will be interpreted as @return ChildClass , for GrandChildClass it will be @return GrandChildClass .

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