Instance child class in abstract static method PHP?

In PHP, you can create instances of child classes within abstract static methods using the new static() syntax. This approach leverages late static binding to instantiate the actual calling class rather than the abstract parent class.

How It Works

The static keyword refers to the class that was actually called at runtime, not the class where the code is written. This allows abstract classes to create instances of their concrete child classes.

Example

The following example demonstrates how to instance a child class in an abstract static method −

<?php
abstract class Base {
    protected static $fullName = '';
    
    abstract protected function customFunction();
    
    public static function get_obj($param1 = null, $param2 = null) {
        $obj = new static(); // Creates instance of calling class
        $obj->customFunction();
        return $obj;
    }
    
    public static function getFullName() {
        return static::$fullName;
    }
}

class Child extends Base {
    protected static $fullName = 'John Doe';
    
    protected function customFunction() {
        echo self::getFullName() . "<br>";
        echo "Object created: " . get_class($this);
    }
}

Child::get_obj();
?>
John Doe
Object created: Child

Key Points

When using new static() in an abstract static method:

  • Late Static Binding: static resolves to the actual calling class at runtime
  • Instance Creation: Creates an object of the child class, not the abstract parent
  • Method Access: The created instance can call both abstract and concrete methods
  • Property Access: Static properties are resolved using late static binding with static::$property

Conclusion

Using new static() in abstract static methods enables flexible object creation patterns where the abstract class can instantiate its concrete implementations. This technique is particularly useful for factory methods and builder patterns.

Updated on: 2026-03-15T09:36:40+05:30

607 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements