Php – Switching from abstract class to interface

abstract classinterfacesPHP

I have an abstract class which has all abstract methods except one which constructs objects of the subclasses. Now my mentor asked me to move this abstract class to an interface.

Having an interface is no problem except with the method used to construct subclass objects. Where should this method go now?

Also, I read somewhere that interfaces are more efficient than abstract classes. Is this true?

Here's an example of my classes

abstract class Animal {
    //many abstract methods
    getAnimalobject(some parameter) {
        return //appropriate subclass 
    }
}

class Dog extends Animal {}
class Elephant extends Animal {}

Best Answer

That construction method should go in a new Factory class.

In object-oriented computer programming, a factory is an object for creating other objects. It is an abstraction of a constructor, and can be used to implement various allocation schemes. For example, using this definition, singletons implemented by the singleton pattern are formal factories.

A factory object typically has a method for every kind of object it is capable of creating. These methods optionally accept parameters defining how the object is created, and then return the created object.

Factory objects are used in situations where getting hold of an object of a particular kind is a more complex process than simply creating a new object. The factory object might decide to create the object's class (if applicable) dynamically, return it from an object pool, do complex configuration on the object, or other things...