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.