Skip to content

Instantly share code, notes, and snippets.

@muratpurc
Created September 22, 2011 09:29
Show Gist options
  • Save muratpurc/1234410 to your computer and use it in GitHub Desktop.
Save muratpurc/1234410 to your computer and use it in GitHub Desktop.
PHP: Traverse object inheritance, creates object tree using the ReflectionClass.
/**
* Builds the class tree, calls itself recursively, if a parent exists.
*
* @param string $name The name of class to create the tree from
* @param int $level Tree level
* @return string The string representation of the tree
*/
function buildClassTree($name, $level=0){
$prefix = str_repeat(' ', ($level * 2));
$tree .= $prefix . $name . "\n";
$rc = new ReflectionClass($name);
if ($parent = $rc->getParentClass()) {
$tree .= buildClassTree($parent->name, ++$level);
}
return $tree;
}
################################################################################
########## Example
// some classes extending each other
class Std extends stdClass {}
class Foo extends Std {}
class Bar extends Foo {}
class Foobar extends Bar {}
echo '<pre>' . buildClassTree('Foobar') . '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment