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?
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With