What is the reasoning behind the refusal of PHP to accept the return types in this simple situation? What is the reasoning behind the refusal of PHP to accept the return types in this simple situation? php php

What is the reasoning behind the refusal of PHP to accept the return types in this simple situation?


You're describing a type-reasoning feature called covariance, which is itself a consequence of the Liskov Substitution Principle.


As of PHP 7.4, this works as you expect. (See the RFC implementing the behavior for details.)


Prior to then, this was discussed on internals. As was stated in one such conversation:

if an implementation better than satisfies the requirements defined by an interface, it should be able to implement that interface.

So, yes, PHP should allow covariance as you describe. But realize: it's not that PHP refuses to implement covariance, it's that PHP has not yet implemented covariance. There are some technical hurdles to doing so, but they're not insurmountable. As was stated in that same thread on internals by a core maintainer:

It's doable, it just hasn't been done.

If you'd like to produce an RFC and a PR, please do so. Until then, it's just an unfortunate status quo of the ever-evolving PHP object system.