Get all defined classes of a parent class in php

If you need that, it really smells like bad code, the base class shouldn't need to know this.

However, if you definitions have been included (i.e. you don't need to include new files with classes you possibly have), you could run:

$children  = array();
foreach(get_declared_classes() as $class){
    if($class instanceof foo) $children[] = $class;
}

Taking Wrikken's answer and correcting it using Scott BonAmi's suggestion and you get:

$children = array();
foreach( get_declared_classes() as $class ){
  if( is_subclass_of( $class, 'foo' ) )
    $children[] = $class;
}

The other suggestions of is_a() and instanceof don't work for this because both of them expect an instance of an object, not a classname.


Use

$allClasses = get_declared_classes();

to get a list of all classes.

Then, use PHP's Reflection feature to build the inheritance tree.

Tags:

Php

Oop

Class