Am 12.05.16 um 18:37 schrieb Marco Perone: > Hi everybody, > I hope this is the right place for asking such a question. If that's not > the case, please excuse me; I'd appreciate if you could redirect me to > the appropriate place. > > The PHP manual says, regarding Interfaces, that 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. > > I don't understand why this needs to be so. Consider for example the > following case: I have an interface > > interface Foo > { > public function foo(SpecialClass $object); > } > > and a class > > class Bar > { > public function foo(BaseClass $object) > { > // do something with BaseClass $object > } > } > > that has the same signature of Foo except for the fact that the method > foo takes a BaseClass, where SpecialClass extends BaseClass. > > From a theoretical point of view, saying that a class satisfies the > interface Foo means that it has a method foo that is able to deal with a > SpecialClass object. So Bar satisfies the contract imposed by Foo since > it has a method foo that is able to deal with a BaseClass, which means > that it will also be able to deal with SpecialClass. > > Hence it would seem natural to say that Bar implements Foo. But, as the > documentation says, this produces a fatal error. > > What is the reason for this fatal error? Is there a specific reason to > do things this way? It this is the case, could you please provide an > example that proves why my approach creates problems. > Thank you > Hey Marco.
It's the other way around. The interface creates a contract that ensures that you can use ALL methods available in your SpecialClass. But that might be more, never less methods than in BaseClass. So when you try to call methods of the SpecialClass while executing Bar::foo() (which you have a contract on) it might fail as BaseClass might not have those methods. class BaseClass { public function a(){} } class SpecialClass extends BaseClass{ public function b(){} } Think about the implementation of your class Bar: class Bar implements Foo { public function foo($x){ $x->b(); } } So calling (new Bar())->foo(new BaseClass()) will fail as the method 'b' isn't implemented, but it should be according to the interface... Hope that helps ;) Cheers Andreas -- ,,, (o o) +---------------------------------------------------------ooO-(_)-Ooo-+ | Andreas Heigl | | mailto:andr...@heigl.org N 50°22'59.5" E 08°23'58" | | http://andreas.heigl.org http://hei.gl/wiFKy7 | +---------------------------------------------------------------------+ | http://hei.gl/root-ca | +---------------------------------------------------------------------+
smime.p7s
Description: S/MIME Cryptographic Signature