Jump to content

Interfaces with type declaration


Recommended Posts

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());

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.