Can you override interface methods with different, but “compatible”, signatures?

后端 未结 7 1163
长发绾君心
长发绾君心 2021-02-07 01:32

Consider the following PHP interfaces:

interface Item {
    // some methods here
}

interface SuperItem extends Item {
    // some extra methods here, not define         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 01:38

    No, I'm pretty sure PHP doesn't support this, in any version, and it would rather defeat the point of an interface.

    The point of an interface is that it gives you a fixed contract with other code that references the same interface.

    For example, consider a function like this:

    function doSomething(Collection $loopMe) { ..... }
    

    This function expects to receive an object that implements the Collection interface.

    Within the function, the programmer would be able to write calls to methods that are defined in Collection, knowing that the object would implement those methods.

    If you have an overridden interface like this, then you have a problem with this, because a SuperCollection object could be passed into the function. It would work because it also is a Collection object due to the inheritance. But then the code in the function could no longer be sure that it knows what the definition of the add() method is.

    An interface is, by definition, a fixed contract. It is immutable.

    As an alternative, you could consider using abstract classes instead of interfaces. This would allow you to override in non-Strict mode, although you'll still get errors if you use Strict Mode, for the same reasons.

提交回复
热议问题