1

I am using a simple extension of the Illuminate Collection class.

class AnimalCollection extends Collection
{
    /** @var Animal[] $items */
    protected $items = [];

    /**
     * @param array-key $key
     * @return Animal
     */
    public function offsetGet($key)
    {
        return $this->items[$key];
    }

    // Plus some other code to ensure only Animals can be inserted
}

However, in for loops, the type of the Collection items is always "mixed". Is there a way to make PHPStorm figure out that this Collection contains Animal objects?

class SomeCode
{
    public function __construct() {

        $animals = new AnimalCollection();

        foreach ($animals as $animal) {
            $animal->makeNoise();
            // Type of 'animal' is mixed, so I don't get type hints. ):
        }

    }

}

I know I can write /** @var Animal $animal */ above every loop to make it work, but that would be suboptimal.

Mike
  • 95
  • 8
  • [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551) – vixducis Jan 09 '22 at 13:18
  • 1
    Does this answer your question? [PHPDoc type hinting for array of objects?](https://stackoverflow.com/questions/778564/phpdoc-type-hinting-for-array-of-objects) – SiZE Jan 09 '22 at 13:33
  • @SiZE I edited my code and type-hinted the offsetGet method, but that doesn't seem to help. – Mike Jan 09 '22 at 14:15
  • `offsetGet` is used for `[]` notation. For example `$animals[0]` should be of your required type. – u_mulder Jan 09 '22 at 17:46
  • 1
    Check this question, maybe it will help https://stackoverflow.com/questions/22272280/proper-phpdoc-comment-for-iteratable-object – u_mulder Jan 09 '22 at 17:49
  • @u_mulder This resolves the issue! – Mike Jan 09 '22 at 19:39

0 Answers0