18

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

liysd
  • 4,413
  • 13
  • 35
  • 38
  • You mean like "hey, PHP, what subclasses are out there for class MyBaseClass"? Probably not, because they may live in files that aren't loaded. – sblom Aug 12 '10 at 16:48

3 Answers3

36
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.

Community
  • 1
  • 1
Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • 2
    Yes, it's just necessary to keep in mind it will only work if the files defining these classes are already (auto)loaded. Great code though. – Camilo Martin Dec 09 '13 at 03:38
3

Using PHP 7.4:

$children = array_filter(get_declared_classes(), fn($class) => is_subclass_of($class, MyClass::class)); 
celsowm
  • 846
  • 9
  • 34
  • 59
-2
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()) : []
    ));
}
gskema
  • 3,141
  • 2
  • 20
  • 39