PHPStorm Type hinting array of different types

前端 未结 2 1917
温柔的废话
温柔的废话 2021-01-12 08:11

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

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


        
2条回答
  •  旧巷少年郎
    2021-01-12 08:41

    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());
    }
    

    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.

    I hope this helped!

提交回复
热议问题