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.
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.