NotionCommotion Posted May 11, 2018 Share Posted May 11, 2018 I am sure I am missing some big concept, and would appreciate some help. DogFactory::create() must be given a DogPrototype object and must return a Dog object, and similarity for CatFactory::create(). The create() method is identical for both a dog or a cat, and I don't wish to duplicate the script in both of these two classes. So, I came up with the following, but it results in a fatal error because "the class implementing the interface must use the exact same method signatures as are defined in the interface" as documented in http://php.net/manual/en/language.oop5.interfaces.php. This seems like a good use, but since by design it results in error, I am obviously missing some core concept of OOP. Can anyone provide some guidance where I am going astray? class AnimalFactory { public function __construct($mapper) { $this->mapper=$mapper; } public function create($prototype) { //bla bla bla script return $this->mapper->make($prototype); } } interface DogFactoryInterface { public function create(DogPrototype $prototype): Dog; } interface CatFactoryInterface { public function create(CatPrototype $prototype): Cat; } class DogFactory extends Animal implements DogFactoryInterface{} class CatFactory extends Animal implements CatFactoryInterface{} class DogPrototype{} class CatInterface{} class DogMapper{} class CatMapper{} $dogFactory=new DogFactory(new DogMapper()); $dog=$dogFactory->create(new DogPrototype()); Quote Link to comment Share on other sites More sharing options...
requinix Posted May 11, 2018 Share Posted May 11, 2018 It obeys the rules of OOP but not the rules of PHP: return types are invariant - they must be the same. IIRC technical limitations that they do want to remove someday. So make Dog and Cat extend Animal, if they aren't already, and have Animal as the return type. Quote Link to comment Share on other sites More sharing options...
NotionCommotion Posted May 11, 2018 Author Share Posted May 11, 2018 Thanks requinix, Don't know if I am happy or said that it is a PHP limitation as the alternative is that it is a me limitation. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.