在phpdoc中根据输入参数值指定@返回类型


specify @return type in phpdoc based on input parameter value

有人知道根据输入参数指定@return类型的方法吗?

我的项目有很多方法调用,比如

...->getComponent('name')->someMethod()

其中getComponent是一个服务定位器,IDE不理解它返回的值

对于PhpStorm IDE,您可以在项目中创建一个或多个称为.phpstorm.meta.php的文件。下面是这样一个文件的示例内容:

<?php
namespace PHPSTORM_META {
    override('Factory::getComponent(), map([
        "name" => 'some'namespace'Name::class,
        "exception" => 'Exception::class,
    ]));
}

你可以在这里找到文档:https://www.jetbrains.com/help/phpstorm/ide-advanced-metadata.html

地图

我建议提交这个文件,使自动完成对其他PhpStorm用户可用

唯一的方法是让getComponent()@return标记实际上列出所有可能返回的数据类型。PHP允许的这种动态、松散的类型行为不利于IDE自动完成的静态解析。这一直是一个很难记录的情况,因为你的API文档就像"静态的";作为"对象树"为了提供自动补全功能,IDE必须构造一个。

如果IDE自动完成非常紧急,需要调整代码来实现它,那么除了我前面的

@return ClassOne|ClassTwo|...|ClassInfinitum option,

您可以将两个调用分开而不是链接它们,并使用@var"本地docblock";一些 ide知道如何识别

// this litte docblock establishes the data type for the local variable $nameComponent
// note however that some IDEs want "datatype varname", 
// some want "varname datatype",
// and some don't recognize the docblock at all
/** @var 'NameClass $myComponent */
$nameComponent = $service->getComponent('name');
// here, the known methods of NameClass should pop up after typing ->
$nameComponent->