Skip to content
PHP Logo

How can a function in an abstract class instantiate the class it belongs to without using a switch or factory in PHP?

To instantiate the class it belongs to without using a switch or factory in PHP, you can utilize late static binding in PHP. By using the static keyword inside the abstract class's static function, you can refer to the class that the method is called on, allowing you to instantiate the class dynamically without explicitly naming it. This approach provides flexibility and avoids the need for conditional logic like switch statements or factories.

php
abstract class AbstractClass {
    public static function instantiateSelf() {
        return new static();
    }
}

class ConcreteClass extends AbstractClass {
    public function __construct() {
        echo "Concrete class instantiated successfully";
    }
}

$instance = ConcreteClass::instantiateSelf();