Covariant template types in collections #40889
-
(see answer below) PhpStan natively treats types of values of arrays (and iterables in general) as covariant, which I think is what people usually expect ( Here's an example, for which PhpStan fails: use Illuminate\Support\Collection;
class FooParent {}
class FooChild extends FooParent {}
interface BarInterface {
/**
* @return Collection<int, FooParent> <-- notice FooParent
*/
public function bar(): Collection;
}
class BarImpl implements BarInterface {
public function bar(): Collection {
return collect([
0 => new FooChild(), // <-- notice FooChild
]);
}
}
If we replace Btw, Psalm supports the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Ah, that's an annoying one. I wish the static analysis community had opted to do the opposite and make covariant the default behaviour, but that's what we got. I'm creating a PR for this. |
Beta Was this translation helpful? Give feedback.
I actually don't think it's a good idea anymore. Covariance makes sense only for read-only collections (see e.g. comments on this SO answer and related article).
Anyway, since it's already been implemented, I guess this can be closed.