Search code examples
phpinheritancestatic-methodsfactory-patternself

How to build a subclass using an inherited factory method defined in the superclass in PHP?


I'm new to PHP. I have three classes, say A, B, and C, where B and C inherit directly from A. My problem is, I need a static factory, say createInstance() that is defined once for class A, and is applicable throughout its descendants. So when someone calls A::createInstance(), it returns an object of type A, while calling B::createInstance() returns an instance of B, and C::createInstance() returns an instance of C. I put the following code inside createInstance() definition in class A:

public static function createInstance() {
    return new self();
}

but that wouldn't be the solution to my needs, since self always refers to class A regardless of what class it's called on. In other words, calling B::createInstance() and C::createInstance always return an object of type A. How can I create such a factory method that returns an object of the appropriate class?


Solution

  • PHP has a static keyword you can use:

    public static function createInstance() {
        return new static();
    }