Get all extended Classes in PHP

2019-01-25 13:41发布

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?

3条回答
混吃等死
2楼-- · 2019-01-25 14:14
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

查看更多
再贱就再见
3楼-- · 2019-01-25 14:23

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.

查看更多
ら.Afraid
4楼-- · 2019-01-25 14:32

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.

查看更多
登录 后发表回答