不同类型的PHPStorm类型提示数组 [英] PHPStorm Type hinting array of different types

查看:98
本文介绍了不同类型的PHPStorm类型提示数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在PHPStorm中使用类型不同的对象类型来提示数组,即:

Is it possible in PHPStorm to type hint an array with different object types, ie:

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

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

Even declaring them separately before building the array doesn't seem to work.

推荐答案

您可以使用phpdocs来使phpstorm接受像这样的多种类型的数组:

you can use phpdocs in order for phpstorm to accept an array of multiple types like so:

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

此技术将使phpstorm认为该数组可以包含这些对象中的任何一个,因此它将为您提供所有这三个对象的类型提示. 或者,您可以使所有对象扩展另一个对象或实现一个接口,然后键入提示,一旦对象或接口如下所示:

This technique will make phpstorm think that the array could contain any of those objects and so it will give you type hinting for all three. Alternatively you can make all of the objects extend another object or implement an interface and type hint that once object or interface like so:

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

这只会为您提供有关类从父类或接口扩展或实现的提示.

This will give you type hints for only what the classes extend or implement from the parent class or interface.

我希望这对您有帮助!

这篇关于不同类型的PHPStorm类型提示数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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