John Davidson

Is there a type hint for an array of objects of a specific class in PHP 8.3?

0 comments
Message:


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;


My Answer:
No, as of PHP 8.3, there is no built-in type hint for an array of objects of a specific class. You can only use type hints for scalar types, arrays, callables, and objects.

You can achieve similar functionality by using a combination of type hints and PHPDoc comments. For example, you can use the following code:

php
/** @var Task[] $tasks */
private array $tasks;


This way, you can still provide type hinting information to your IDE and other developers, even though it is not a native PHP type hint.

Rate this post

3 of 5 based on 6972 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us