Jump to content
Sign in to follow this  
NotionCommotion

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

 

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

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.