mushroom
mushroom

Reputation: 1945

PHP OOP: Get all declared classes which are have extended another parent class

I need to get all declared classes which are have extended another parent class.

So for example...

class ParentClass {

}

class ChildOne extends ParentClass {

}

class ChildTwo extends ParentClass {

}

class ChildThree {

}

I need an array that outputs this:

array('ChildOne', 'ChildTwo')

I'm new to PHP OOP, but based on some Googling, I came up with this solution.

$classes = array();

foreach( get_declared_classes() as $class ) {
    if ( is_subclass_of($class, 'ParentClass') ){
        array_push($classes, $class);
    }
}

What I want to ask is whether this is the best practice to do what I want to do, or is there a better way? The global scope will contain a lot of other classes that isn't a child of ParentClass. Is looping through all declared classes the best way to go?

EDIT (clarification of purpose):

What I want to achieve with this is to instantiate each child class extending the parent class.

I want to do $childone = new ChildOne; $childtwo = new ChildTwo; for every child of ParentClass.

Upvotes: 4

Views: 1642

Answers (2)

artragis
artragis

Reputation: 3713

you can try to log the declaration of a class the first time it is loaded. it suppose you are using autoloading.

if you do not use composer but a custom loader :

It's the easiest way :

$instanciatedChildren = array();//can be a static attribute of the A class 
spl_autoload_register(function($class)use($instanciatedChildren){
   //here the code you use 
   if(is_subclass_of($class,'A')){
       $instanciatedChildren[] = $class;
   }
 }

if you use composer :

you can, make a class that extends composer/src/Composer/Autoload/ClassLoader.php and then override the loadClass method to add the condition given above. and then register your new loader and unregister the old one.

Upvotes: 2

Ray
Ray

Reputation: 41428

Your solution seems fine, though I'm not sure why you'd do this. There is no easy way in php to say, 'give me all the declared classes of a certain parent class globally' without actually checking globally each declared class. Even if you have a couple hundred classes loaded to loop through, it shouldn't be too heavy as they're all in memory.

If you're trying to just track loaded child classes for a specific parent, why not create a registry that tracks them when they're loaded? You could do this tracking in an autoloader or factory used for the child classes or event as a hack, just by putting something at the top of the class file before the class definition.

Upvotes: 1

Related Questions