Is there a type hint in PHP 8.3
which allows using ExampleClass[]
for declaring it is an array of objects of the class ExampleClass
?
In my specific case, ExampleClass
is called Task
What I want but does not work:
private Task[] $tasks;
My PHPStorm IDE tells me that Plural types are allowed only in doc types
- speaking that only in PHPDoc
using Tasks[]
would be totally fine. But I want to use plain PHP.
The error is:
PHP Parse error: syntax error, unexpected token "[", expecting variable
If I would only need one object Task
and not an array of objects Task[]
it would work with:
private Task $task;
This is my current, working workaround:
private array $tasks;
The short answer is no.
My understanding is that enforcing such a thing has terrible performance problems. Some people want to go all the way and have full blown generics, others just want type-safe collections. Some people worry that implementing the latter first might hinder the development of the former in the future. So we’re at a standstill.
There’s the occasional discussion in the community such as this: https://externals.io/message/108175
Edit Depending on how you interpret the question, @Pierre's answer could be considered more correct, since the OP said "type hint", although they showed a "type declaration".
There's a good thread from a while back arguing about the implications of what to call it, and that PHP's implementation is not a hint but a declaration. Some people argued that although calling it a "hint" is a misnomer, that shipped sailed and no matter what core changes, the community would still call it a hint. They did eventually update the documentation, however, to use "type declaration".
Personally, I find myself still saying "type hint" for the explicit type declaration, but I try to catch and correct myself. I do this because I'm trying to change my mindset so that if I talk to a non-PHP person (usually a JavaScript person), they know that I'm not talking about IDE hints but true language features.
Edit There’s a great post on the PHP Foundation's blog that shows the state of things as of August of 2024: State of Generics and Collections