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

僤鯓⒐⒋嵵緔 提交于 2020-01-05 04:34:11

问题


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.


回答1:


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.




回答2:


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);
?>


来源:https://stackoverflow.com/questions/7880862/can-one-output-the-full-inheritance-chain-of-a-class-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!