Home » Php » class – Get all extended Classes in PHP

class – Get all extended Classes in PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

Say I got a class like:

<?
class ObjectModel {
}

and I got some other classes like:

<?
class SomeNewClass extends ObjectModel {
}

class SomeOtherNewClass extends ObjectModel {
}

Is there a way to get the children (SomeNewClass & SomeOtherNewClass) based on the ObjectModel class?

How to&Answers:
class ObjectModel {
}

class SomeNewClass extends ObjectModel {
}

class SomeOtherNewClass extends ObjectModel {
}

class SomeOtherNewClassLol extends ObjectModel {
}

function get_extends_number($base){
    $rt=0;
  foreach(get_declared_classes() as $class)
        if(is_subclass_of($class,$base)) $rt++;
        return $rt;
}

echo get_extends_number('ObjectModel'); //output: 3

Yes, you can do it, DEMO

Answer:

You can iterate all classes returned by get_declared_classes() and inspecting their Reflection (Reflection::isSubclassOf)

But – this won’t work when you are using autoloading.

Answer:

Not sure if this is going to get downvoted but you can hack your way through:

  1. get_declared_classes
  2. get_parent_class for each class on 1

It’s not pretty, but if the child classes are loaded, it’s possible.