Can one output the full inheritance chain of a class in PHP?

Given

class a{...}
class b extends a{...}
class c extends b{...}
class d extends c{...}

Is there a way, from an instance of class d, to show that it's class definition extends c which extends b which extends a? Is there a way to do it statically given the class name?

I get tired of crawling from file to file figuring out what extends what, and so on.

Upvotes: 2

Views: 824

Answers (2)

alexantd
alexantd

Reputation: 3605

You want to use ReflectionClass. Someone has posted an answer of how to do this with code here: http://www.php.net/manual/en/reflectionclass.getparentclass.php

<?php
$class = new ReflectionClass('whatever');

$parents = array();

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

echo "Parents: " . implode(", ", $parents);
?>

Upvotes: 4

AndersTornkvist
AndersTornkvist

Reputation: 2629

I often use:

<?php
class grandfather {}
class father extends grandfather {}
class child extends father {}

function print_full_inheritance($class) {
  while ($class!==false) {
    echo $class . "\n";
    $class = get_parent_class($class);
  }
}

$child = new child();
print_full_inheritance(get_class($child));

?>

You could read more in PHP manual at http://php.net/manual/en/function.get-parent-class.php.

Upvotes: 5

Related Questions