Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OOP "Implementation must be compatible" [duplicate]

Tags:

oop

php

I'm having weird problems with PHP OOP and type hinting. Here's an example:

abstract class AC {}

class C extends AC {}

interface I {
    function method(AC $abstract);
}

class InterfaceImplementation implements I {
    function method(C $concrete) {}
}

This code won't run, saying that method is not compatible with the interface declaration. I would think it is compatible since C extends AC - do I miss something? How am I expected to implement this sort of functionality?

like image 996
Fluffy Avatar asked Jan 14 '12 14:01

Fluffy


2 Answers

Imagine you have a class B which also extends AC. Then I requires that any of its implementations also accept B as argument to method. Your InterfaceImplementation, however, doesn't.

The bigger picture: You might want to reconsider your design if you need to specify a concrete type in the implementation. The idea is that to the outside world, all that needs to be known is encoded by AC and there should not be an InterfaceImplementation that ever needs to know which concrete subclass is being transferred. Maybe the specific stuff can be embedded in C's code and generically called through a method exposed by AC?

Yet another update: You might be able to achieve what you want using generics, but I don't think they exist in PHP. I still think if you share the details of the design problem that might make another interesting question :)

like image 122
Nicolas78 Avatar answered Oct 31 '22 15:10

Nicolas78


Just define it as :

class InterfaceImplementation implements I {
    function method(AC $concrete) {}
}

And call it with an instance of C, ie. ->method(new C());.

The PHP reference manual on Object Interfaces clearly states :

The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

like image 40
wimvds Avatar answered Oct 31 '22 16:10

wimvds