如何告诉phpDoc字符串是类名?

Rob*_*ert 7 php phpdoc phpstorm

我经常给对象提供静态方法和属性,这些方法和属性不需要初始化对象。例如:

class SomeObject {
    public function __construct($object_id) {
        $this->loadProperties($object_id);
    }

    public static function getSomeStaticString() {
        return "some static string";
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我们对这些对象进行了子类化,并具有某种控制器,该控制器在某些尚不应该初始化对象的情况下返回对象类字符串。例如:

class SomeObjectController {
    public function getSomeObjectWithTheseProperties(array $properties) {
        if($properties[0] === "somevalue") {
            if($properties[1] === "someothervalue") {
                return SomeSubclassObject::class;
            }

            return SomeObject::class;
        }

        return NULL;
    }
}
Run Code Online (Sandbox Code Playgroud)

有时我可能想在SomeObject::getSomeStaticString()不实际初始化对象的情况下调用静态函数(因为这将涉及不需要的数据库提取)。例如:

$controller = new SomeObjectController;
$properties = array("somevalue", "someothervalue");
$object_class = $controller->getSomeObjectWithTheseProperties($properties);

echo $object_class::getSomeStaticString();
Run Code Online (Sandbox Code Playgroud)

问题:我可以以某种方式最好通过phpDoc告诉PhpStorm,它$object_class是的子类的类字符串SomeObject吗?

如果我告诉我的IDE它是一个字符串,它将通知我这getSomeStaticString()是一个无效方法。另一方面,如果我告诉我的IDE是SomeObject的实例,它认为我可以访问常规的非静态方法和属性,而我不能。

Bar*_*art 15

class-stringPHPStan为此使用PHPDoc 类型。PHPStorm 自2020.3起就开始支持它,但从2021.2开始,它似乎可以正常工作(所有自动完成功能都可用),当时他们添加了对泛型的支持。

在您的情况下,返回类型注释将是@return class-string<SomeObject>.

  • 令人遗憾的是 `class-string` 没有解析 PhpStorm 中类的静态方法。 (3认同)
  • 仅供参考:PhpStorm **2020.3** 将拥有自己的 PHPStan/Psalm 集成插件:https://blog.jetbrains.com/phpstorm/2020/10/phpstorm-2020-3-eap-2/ 并且您引用的插件可能不再适用于较新的 IDE 版本(部分相关评论:https://youtrack.jetbrains.com/issue/WI-54439#focus=Comments-27-4444560.0-0) (2认同)