Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to obtain all subclasses of a class in php

Is it possible to get all subclasses of given class in php?

like image 719
liysd Avatar asked Aug 12 '10 16:08

liysd


People also ask

How do you find all the subclasses of a class given its name?

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.

What is a subclass in PHP?

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.

How can we inherit properties in PHP?

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.

Does PHP have inheritance?

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.


2 Answers

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.

like image 60
Artefacto Avatar answered Nov 01 '22 09:11

Artefacto


Using PHP 7.4:

$children = array_filter(get_declared_classes(), fn($class) => is_subclass_of($class, MyClass::class)); 
like image 45
celsowm Avatar answered Nov 01 '22 09:11

celsowm