Specifying Type Hints for Arrays of Objects in PHPDoc
To declare a PHPDoc tag for an array of objects, use the following syntax:
@var array<\Fully\Qualified\Class\Name>
For example:
/** @var SomeObj[] */ private $someObjInstances;
This syntax informs the IDE that the $someObjInstances variable is an array of SomeObj objects. The IDE will then provide appropriate code insights and type checking when working with that variable.
IDE Support
Note that not all IDEs support this syntax for arrays of objects. For example, PHPEd may not recognize it. However, popular IDEs like PhpStorm and Visual Studio Code support it out of the box.
Alternative Syntax
In PHP 8.1, an alternative syntax was introduced for specifying the type of elements within an array:
@var array{key: type, key: type, ...}
For example:
/** @var array{object: SomeObj, string: string} */ private $someObjsArray;
This syntax allows you to specify the types of specific keys within the array. It is particularly useful when dealing with associative arrays.
The above is the detailed content of How Can I Specify Type Hints for Arrays of Objects in PHPDoc?. For more information, please follow other related articles on the PHP Chinese website!