PHPStorm Type hinting array of different types

前端 未结 2 1900
温柔的废话
温柔的废话 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!

    0 讨论(0)
  • 2021-01-12 08:43

    This is described in the PHPDoc standards

    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())
    {
        <...>
    }
    
    0 讨论(0)
提交回复
热议问题