Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all defined classes of a parent class in php

Tags:

oop

php

class

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'); 
like image 363
Trey Avatar asked Jul 12 '11 21:07

Trey


People also ask

What is the parent class of parent class?

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.

How do you call a parent class in PHP?

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();

What is parent :: in PHP?

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.


2 Answers

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; } 
like image 50
Wrikken Avatar answered Sep 25 '22 03:09

Wrikken


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.

like image 23
MikeSchinkel Avatar answered Sep 25 '22 03:09

MikeSchinkel