Reputation: 1945
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
Reputation: 3713
you can try to log the declaration of a class the first time it is loaded. it suppose you are using autoloading.
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;
}
}
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
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