I need to determine, after all files have been included, which classes extend a parent class, so:
class foo{ } class boo extends foo{ } class bar extends foo{ }
and I'd like to be able to grab an array like:
array('boo','bar');
In the object-oriented programming, we can inherit the characteristics of parent class. Parent class is known as base class while child class is known as derived class. The derived class can inherit data members, member functions of base class.
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private). $obj = new OtherSubClass();
parent:: is the special name for parent class which when used in a member function.To use the parent to call the parent class constructor to initialize the parent class so that the object inherits the class assignment to give a name. NOTE: PHP does not accept parent as the name of a function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With