mercredi 28 janvier 2015

Get an array of classes inheritances

I am trying to generate a multidimensional array of the inheritances tree from a given list of classes.


Input ['A', 'B', 'C', 'D']



class A {}

class B extends A {}

class C extends A {}

class D extends C {}


The desired output would be something like this



[
'A' => false,
'B' => [
'A' => false
],
'C' => [
'A' => false
],
'D' => [
'C' => [
'A' => false
]
]
]


I could not go any further then this without a headache.



function getTree(array $classes) {
$paths = [];

foreach($classes as $class) {
if (! class_exists($class))
continue;

$class = new ReflectionClass($class);

if (! isset($paths[$class->getName()]))
$paths[$class->getName()] = false;

while($parent = $class->getParentClass()) {
$paths[$class->getName()] = $parent->getName();
$class = $parent;
}
}

return $paths;
}

$tree = getTree(['A', 'B', 'C', 'D']);

print_r($tree);

Array
(
[A] =>
[B] => A
[C] => A
[D] => C
)


Anyone got a hint to help me accomplish this?


Thank you






Aucun commentaire:

Enregistrer un commentaire