liysd
liysd

Reputation: 4623

how to obtain all subclasses of a class in php

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

Upvotes: 19

Views: 12306

Answers (3)

gskema
gskema

Reputation: 3221

function getClassNames(string $className): array
{
    $ref = new ReflectionClass($className);
    $parentRef = $ref->getParentClass();

    return array_unique(array_merge(
        [$className],
        $ref->getInterfaceNames(),
        $ref->getTraitNames(),
        $parentRef ?getClassNames($parentRef->getName()) : []
    ));
}

Upvotes: -2

celsowm
celsowm

Reputation: 404

Using PHP 7.4:

$children = array_filter(get_declared_classes(), fn($class) => is_subclass_of($class, MyClass::class)); 

Upvotes: 5

Artefacto
Artefacto

Reputation: 97835

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.

Upvotes: 37

Related Questions