Is it possible to get all subclasses of given class in php?
Asked
Active
Viewed 1.1k times
18
-
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 Answers
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.
-
2Yes, 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
-
Looks like PHP 8.0 for me. But still upvoting because of the clean oneliner alternative – Mark Walet Aug 25 '21 at 11:31
-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