Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
staticresolves 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.
