Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface implementation: declaration must be compatible

I have the interface:

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

And classes:

class ActiveRecordBase
{
   ...
}

class Product extends ActiveRecordBase
{
   ...
}

========

But I can't do this:

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

or this:

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

I've got the error "declaration must be compatible"

Is there a way to do this in PHP?

like image 841
violarium Avatar asked Oct 02 '13 06:10

violarium


1 Answers

No, an interface must be implemented exactly. If you restrict the implementation to a more specific subclass, it's not the same interface/signature. PHP doesn't have generics or similar mechanisms.

You can always manually check in code, of course:

if (!($object instanceof Product)) {
    throw new InvalidArgumentException;
}
like image 110
deceze Avatar answered Oct 09 '22 06:10

deceze