使用 Class 的 getInstance 方法时,PhpStorm 没有自动完成功能

PhpStorm no autocomplete when using getInstance method of a Class

有人能告诉我为什么当我使用 getInstance() 方法而不是新的 ClassName 时自动完成不起作用吗?

以下是class的getInstance()方法:

// Define The Namespace For Our Library
namespace JUnstoppable;

class JUnstoppable 
{
    // Instance Of The Class
    protected static $instance = array ();

    public static function getInstance ($forPlatformName = 'joomla')
    {
        $forPlatformName = strtolower($forPlatformName);

        if (!isset(static::$instance[$forPlatformName]))
        {
            static::$instance[$forPlatformName] = new \JUnstoppable\JUnstoppable($forPlatformName);
        }

        return static::$instance[$forPlatformName];
    }

    public function __construct ($platformName = 'joomla')
    {
    }

    public function doExecute ($test = 'lalala')
    {
        return $test;
    }
}

Can somebody tell me why the autocompletion doesn't work when I'm using a getInstance() method instead of new ClassName?

那是因为 IDE 不知道您的 $instance 静态 属性 中可以包含什么,因此它无法弄清楚 getInstance() return 是什么。从 IDE 的角度来看,它只是普通数组(任何类型的元素)而不是 JUnstoppable 个实例的数组。

您可以将插入符号放在 $test 上并调用 View | Quick Documentation 以查看 IDE 对该变量的了解。如果它没有说 JUnstoppable 那也就不足为奇了。


只需通过 PHPDoc's @return 标签为 getInstance() 方法的 return 值添加正确的类型提示:

/**
 * My super method.
 *
 * @param string $forPlatformName Optional parameter description
 * @return JUnstoppable
 */
public static function getInstance ($forPlatformName = 'joomla')

您可以指定具体的 class(在本例中为 JUnstoppable).. 或者 static 如果子 class 也将使用此方法并且他们将 return 个不同的实例。


或者(或者更好地说:另外)你可以键入提示 $instance 属性 IDE 将使用它来找出 getInstance() 方法 return小号:

/** @var JUnstoppable[] Instance Of The Class */
protected static $instance = array ();