Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPStorm Type hinting array of different types

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.

like image 364
Edson Medina Avatar asked Mar 20 '15 11:03

Edson Medina


2 Answers

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!

like image 140
Jason Gallavin Avatar answered Nov 14 '22 12:11

Jason Gallavin


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())
{
    <...>
}
like image 5
beardedlinuxgeek Avatar answered Nov 14 '22 12:11

beardedlinuxgeek