PHP OOP: get all declared classes that extend another parent class

I need to get all declared classes that 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 am 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); } } 

I want to ask if this is the best practice to do what I want to do, or is there a better way? The global scope will contain many other classes that are not children of the ParentClass . Is looping all declared classes the best way?

EDIT (goal clarification):

I want to achieve this in order to instantiate each child class extending the parent class.

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

+4
source share
2 answers

Your decision seems fine, although I'm not sure why you will. There is no easy way in php to say: "Give me all the declared classes of a specific parent class globally" without checking globally every declared class. Even if you have a couple of hundreds of classes loaded in a loop, they should not be too heavy, because they are all in memory.

If you're trying to just keep track of the loaded child classes for a specific parent, why not create a registry that keeps track of them at boot time? You can do this tracking in the autoloader or factory used for child classes or events, how to hack by simply placing something at the top of the class file before defining the class.

+1
source

you can try to write a class declaration on first boot. Suppose you are using autoload.

if you are not using a composer but a custom loader:

This is 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 above. and then register a new bootloader and unregister the old one.

+2
source

All Articles