【问题标题】:PHPStorm Type hinting array of different typesPHPStorm 类型提示不同类型的数组
【发布时间】:2015-05-23 19:21:06
【问题描述】:

在 PHPStorm 中是否可以键入提示具有不同对象类型的数组,即:

public function getThings()
{
    return array (new Thing(), new OtherThing(), new SomethingElse());
}

即使在构建数组之前单独声明它们似乎也不起作用。

【问题讨论】:

  • 是的。 “PHP 5 引入了类型提示。函数现在能够将参数强制为对象(通过在函数原型中指定类的名称)、接口、数组(自 PHP 5.1 起)php.net/manual/en/language.oop5.typehinting.php - 除非我完全误解了你的问题。
  • 我说的是 PHPStorm(一个 IDE)@ʰᵈˑ
  • 嗯,好的,that edit 解决了我对这个问题的困惑。我的错。
  • PhpStorm 不支持单个数组元素的类型提示(尤其是数字键)。现在存在的那些票都是关于传入数据的(描述数组类型参数的结构)。可能的建议:list($a, $b, $c) = $object->getThings();,然后输入提示单个变量。
  • 如果这个对象实现了一个接口,那么它就是bossile。在方法中添加 phpdoc 注释。当您遍历此对象的数组时,Phpstorm 会建议对象方法。

标签: php phpstorm type-hinting


【解决方案1】:

您可以使用 phpdocs 让 phpstorm 接受多个类型的数组,如下所示:

/**
* @return Thing[] | OtherThing[] | SomethingElse[]
*
*/
public function getThings()
{
    return array (new Thing(), new OtherThing(), new SomethingElse());
}

这种技术会让 phpstorm 认为数组可以包含这些对象中的任何一个,因此它会为您提供所有三个对象的类型提示。 或者,您可以使所有对象都扩展另一个对象或实现一个接口并键入曾经的对象或接口的提示,如下所示:

/**
* @return ExtensionClass[]
*
*/
public function getThings()
{
    return array (new Thing(), new OtherThing(), new SomethingElse());
}

这将为您提供有关类从父类或接口扩展或实现的内容的类型提示。

我希望这会有所帮助!

【讨论】:

  • 你可以写@return (Thing|OtherThing|SomethingElse)[]。不是说有 3 种可能的返回类型,而是说唯一的返回类型是数组,但数组值可以是这些不同的类型。这是一个微妙的区别。
【解决方案2】:

这在 PHPDoc 标准中有描述

https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#713-param

/**
 * Initializes this class with the given options.
 *
 * @param array $options {
 *     @var bool   $required Whether this element is required
 *     @var string $label    The display name for this element
 * }
 */
public function __construct(array $options = array())
{
    <...>
}

【讨论】:

  • 目前(2019 年 9 月)该链接没有帮助,因为该 PSR 中的标签列表已被删除,并且尚未转换为新的 PSR。但是,这预计会在未来的某个时候发生。
  • 这是对a different question 的一个很好的回答,但不是这里问的那个;)
猜你喜欢
  • 1970-01-01
  • 2015-12-08
  • 2015-03-30
  • 2019-03-08
  • 2021-12-26
  • 2013-07-14
  • 2018-08-15
  • 2014-08-29
  • 2015-11-10
相关资源
最近更新 更多