PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 5, 2022

[FIXED] Is there a type hint for an array of objects of a specific class in PHP 8.1?

 March 05, 2022     php, php-8.1, type-hinting     No comments   

Issue

Is there a type hint in PHP 8.1 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;

Solution

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. So we’re at a standstill.

There’s the occasional discussion in the community such as this: https://externals.io/message/108175



Answered By - Chris Haas
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing