PhpStorm-如何正确键入提示数组键?

关于如何使用PhpDoc注释数组键还有一个未解决的问题:https://github.com/phpDocumentor/phpDocumentor2/issues/650

我尝试了以下符号:

/**
 * @return array<string,Someclass>
 * @return Someclass[string]
 */    
public function someMethod(): array { ... }

,但是PhpStorm似乎无法解决此问题,因此在使用例如  foreach内部对象是未知的:

foreach($obj->someMethod() as $some) {
   $some->methodOfSomeclass(); // PhpStorm -> Method not found
}

我知道我可以使用管道运算符:

@return array<string,Someclass>|Someclass[]

我也知道我可以输入提示变量:

/** @var Someclass $obj */
$obj

但是有没有一种方法可以配置PhpStorm在不使用管道的情况下知道数组值类型?

wuyangzhijy 回答:PhpStorm-如何正确键入提示数组键?

在PHP中,您要么具有带有整数键的数字索引数组,要么具有带字符串键的关联数组。由于动态键入,您可以将它们混合使用,因此可以同时使用两种类型。

在您的示例中,您使用的不是密钥,而是值ClassName[]

/**
 * @return Class[]
 */
function getClasses(): array {
  return [new Class()];
}

通过这种模仿,PHPStorm将在forEach循环中提供有效的工具提示。 否则,您可以使用内嵌@type注释。

foreach ($objs as $obj) {
  /* @type Class $obj */
  $obj->someMethod(); //Is hinted
}
本文链接:https://www.f2er.com/3160555.html

大家都在问