PHP - Inheriting an interface - declaration must be compatible

I have an interface:

interface AbstractMapper { public function objectToArray(ActiveRecordBase $object); } 

And classes:

 class ActiveRecordBase { ... } class Product extends ActiveRecordBase { ... } 

========

But I can not do this:

 interface ExactMapper implements AbstractMapper { public function objectToArray(Product $object); } 

or that:

 interface ExactMapper extends AbstractMapper { public function objectToArray(Product $object); } 

I have an error "Ad must be compatible "

So, is there a way to do this in PHP?

+7
inheritance php interface
source share
2 answers

No, the interface must be accurately implemented. If you restrict the implementation to a specific subclass, this is not the same interface / signature. PHP has no generics or similar mechanisms.

Of course, you can always check the code manually:

 if (!($object instanceof Product)) { throw new InvalidArgumentException; } 
+10
source share
 interface iInvokable { function __invoke($arg = null); } interface iResponder extends iInvokable { /** Bind next responder */ function then(iInvokable $responder); } class Responder implements iResponder { function __invoke($arg = null) { // TODO: Implement __invoke() method. } /** Bind next responder */ function then(iInvokable $responder) { // TODO: Implement then() method. } } class OtherResponder implements iResponder { function __invoke($arg = null) { // TODO: Implement __invoke() method. } /** Bind next responder */ function then(iInvokable $responder) { // TODO: Implement then() method. } } class Invokable implements iInvokable { function __invoke($arg = null) { // TODO: Implement __invoke() method. } } $responder = new Responder(); $responder->then(new OtherResponder()); $responder->then(new Invokable()); 
-3
source share

All Articles