Can you override interface methods with different, but "compatible", signatures?
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.
As a workaround I'm using PHPDoc blocks in interfaces.
interface Collection {
/**
* @param Item $item
*/
public function add($item);
// more methods here
}
interface SuperCollection extends Collection {
/**
* @param SuperItem $item
*/
public function add($item);
// more methods here that "override" the Collection methods like "add()" does
}
This way, in case you are properly using interfaces, IDE should help you catch some errors. You can use similar technique to override return value types as well.