【问题标题】:Determining class hierarchy of an object at runtime在运行时确定对象的类层次结构
【发布时间】:2010-11-17 21:10:54
【问题描述】:

get_class() 会给我一个对象的最终类。

我想知道所有的父类链。如何做到这一点?

【问题讨论】:

    标签: php


    【解决方案1】:

    你可以使用

    例子:

    print_r(class_parents('RecursiveDirectoryIterator'));
    

    会输出

    Array
    (
        [FilesystemIterator] => FilesystemIterator
        [DirectoryIterator] => DirectoryIterator
        [SplFileInfo] => SplFileInfo
    )
    

    【讨论】:

      【解决方案2】:

      你可以反复调用get_parent_class直到它返回false

      function getClassHierarchy($object) {
          if (!is_object($object)) return false;
          $hierarchy = array();
          $class = get_class($object);
          do {
              $hierarchy[] = $class;
          } while (($class = get_parent_class($class)) !== false);
          return $hierarchy;
      }
      

      【讨论】:

        【解决方案3】:

        如果您想检查特定类型,或构建一个函数来创建向下钻取而不使用任何其他解决方案,您可以诉诸“instanceof”来确定它是否也是特定类型,这对于检查来说是正确的如果一个类扩展了一个父类。

        【讨论】:

          【解决方案4】:

          PHP Reflection APIReflectionClass 类部分有一个getParentClass() 方法。

          这是一个使用它的小代码示例:

          <?php
          
          class A { }
          class B extends A { }
          class C extends B { }
          
          
          $class = new ReflectionClass('C');
          echo $class->getName()."\n";
          while ($class = $class->getParentClass()) {
            echo $class->getName()."\n";
          }
          

          Run the code

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-10-10
            • 1970-01-01
            • 2012-05-02
            • 1970-01-01
            相关资源
            最近更新 更多