I am working on a PHP project in which a lot of classes are high leveled in the class tree, i.e. they have a lot of parent classes.
At some level, consider there is a class Food, which has quite a lot of subclasses and sub-subclasses etc. I want to implement a method getFoodClasses() in class Food that gives me an array of all subclasses that lead to the current instance, i.e. classes in the tree between class Food and the current instance, including the latter. The Food class itself and all its superclasses should not be included in the result.
Example: if a subclass of Food would be Vegetable, which has a subclass Fruit, which then has a subclass Banana, then the result of on (Banana) $b->getFoodClasses(), needs to result in `array(‘Vegetable’, ‘Fruit’, ‘Banana’).
So,
class Food extends SomeBaseClass
{
public function getFoodClasses()
{
/* Here goes the magic! */
}
}
class Vegetable extends Food {}
class Fruit extends Vegetable {}
class Banana extends Fruit {}
$b = new Banana;
print_r($b->getFoodClasses());
Which results in:
Array
(
[0] => Vegetable
[1] => Fruit
[2] => Banana
)
I ended up with this function.