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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.