如何告诉 phpDoc 一个字符串是一个类名? [英] How to tell phpDoc a string is a class name?

查看:52
本文介绍了如何告诉 phpDoc 一个字符串是一个类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I often give objects static methods and properties that do not require the object to be initialized. For example:

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

    public static function getSomeStaticString() {
        return "some static string";
    }
}

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

Now we subclass these objects and have some sort of controller that returns an object class string under certain circumstances where the object should not yet be initialized. For example:

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

            return SomeObject::class;
        }

        return NULL;
    }
}

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

At times I might want to call the static function SomeObject::getSomeStaticString() without actually initializing the object (because that would involve an unneeded database fetch). For instance:

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

echo $object_class::getSomeStaticString();

问题:我能否以某种方式告诉 PhpStorm,最好通过 phpDoc,$object_classSomeObject 的子类的类字符串?

Question: can I somehow tell PhpStorm, preferably through phpDoc, that $object_class is a class string of a subclass of SomeObject?

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

If I tell my IDE it's a string, it will notify me getSomeStaticString() is an invalid method. On the other hand, if I tell my IDE it's an instance of SomeObject, it thinks I can access regular non-static methods and properties, which I can't.

推荐答案

/** @var SomeObject $object_class */
$object_class = $controller->getSomeObjectWithTheseProperties($properties);

抱歉,没有其他方法可以说明它是 SomeObject 的一个实例.

Sorry, no other way as to tell that it's an instance of SomeObject.

...如果我告诉我的 IDE 它是 SomeObject 的一个实例,它认为我可以访问常规的非静态方法和属性,而我不能.

... if I tell my IDE it's an instance of SomeObject, it thinks I can access regular non-static methods and properties, which I can't.

所以?只是不要访问非静态方法和属性.

So? Just do not access non-static methods and properties.

这篇关于如何告诉 phpDoc 一个字符串是一个类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆