Is it possible to get all subclasses of given class in php?
If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__ as above. However you find the class, cls. __subclasses__() would then return a list of its subclasses.
Subclassing in PHPOnce a class has been defined it is possible to create a new class derived from it that extends the functionality of the original class. The parent class is called the superclass and the child the subclass. The whole process is referred to as subclassing.
Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.
Inheritance is an important principle of object oriented programming methodology. Using this principle, relation between two classes can be defined. PHP supports inheritance in its object model. PHP uses extends keyword to establish relationship between two classes.
function getSubclassesOf($parent) {
$result = array();
foreach (get_declared_classes() as $class) {
if (is_subclass_of($class, $parent))
$result[] = $class;
}
return $result;
}
Coincidentally, this implementation is exactly the one given in the question linked to by Vadim.
Using PHP 7.4:
$children = array_filter(get_declared_classes(), fn($class) => is_subclass_of($class, MyClass::class));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With