IDE phpdoc type hints for properties with attributes

22 Views Asked by At

I'm working with PHP and I've encountered a challenge with IDE support for typed arrays. Here's a snippet of my code:

<?php

class User extends BaseData
{
    public function __construct(
        public string $name,
        
        #[ArrayOf(Hobby::class)]
        public array $hobbies,
    ) {
    }
}

In this code, I'm using an attribute (#[ArrayOf(Hobby::class)]) to indicate that $hobbies is an array of Hobby objects. However, my IDE only recognizes $hobbies as a generic array, so I don't get any specific hints or autocompletion for Hobby objects.

To work around this, I added a PHPDoc comment:

class User extends BaseData
{
    public function __construct(
        public string $name,

        #[ArrayOf(Hobby::class)]
        /** @var Hobby[] */
        public array $hobbies,
    ) {
    }
}

While this helps with IDE hints, I'm looking for a way to rely solely on attributes for IDE support, without having to use PHPDoc comments. Is there a way to adjust the PHPDoc in the attribute class itself, or another approach to achieve this?

Ideally, I'd like to find a solution that allows me to use attributes exclusively for specifying array types, to make my code cleaner and reduce the need for additional comments.

Any advice or suggestions on how to improve IDE recognition of typed arrays using attributes would be greatly appreciated!

0

There are 0 best solutions below