Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all extended Classes in PHP

Say I got a class like:

<?
class ObjectModel {
}

and I got some other classes like:

<?
class SomeNewClass extends ObjectModel {
}

class SomeOtherNewClass extends ObjectModel {
}

Is there a way to get the children (SomeNewClass & SomeOtherNewClass) based on the ObjectModel class?

like image 559
Andre Zimpel Avatar asked May 21 '13 21:05

Andre Zimpel


People also ask

Can PHP extend multiple classes?

Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.

How can I inherit in PHP?

Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.

What is the purpose of $this and extends in PHP?

Definition and Usage The extends keyword is used to derive a class from another class. This is called inheritance. A derived class has all of the public and protected properties of the class that it is derived from.

Can child classes override properties of their parents?

In the same way that the child class can have its own properties and methods, it can override the properties and methods of the parent class. When we override the class's properties and methods, we rewrite a method or property that exists in the parent again in the child, but assign to it a different value or code.


2 Answers

class ObjectModel {
}

class SomeNewClass extends ObjectModel {
}

class SomeOtherNewClass extends ObjectModel {
}

class SomeOtherNewClassLol extends ObjectModel {
}

function get_extends_number($base){
    $rt=0;
  foreach(get_declared_classes() as $class)
        if(is_subclass_of($class,$base)) $rt++;
        return $rt;
}

echo get_extends_number('ObjectModel'); //output: 3

Yes, you can do it, DEMO

like image 180
Sam Avatar answered Sep 27 '22 23:09

Sam


You can iterate all classes returned by get_declared_classes() and inspecting their Reflection (Reflection::isSubclassOf)

But - this won't work when you are using autoloading.

like image 20
jasir Avatar answered Sep 27 '22 21:09

jasir