10

get_class() will give me the eventual class of an object.

I want to know all the chain of parent classes. How can this be done?

MrWhite
  • 43,179
  • 8
  • 60
  • 84
shealtiel
  • 8,020
  • 18
  • 50
  • 82

4 Answers4

31

You can use

  • class_parents — Return all parent classes of the given class in an array

Example:

print_r(class_parents('RecursiveDirectoryIterator'));

will output

Array
(
    [FilesystemIterator] => FilesystemIterator
    [DirectoryIterator] => DirectoryIterator
    [SplFileInfo] => SplFileInfo
)
MrWhite
  • 43,179
  • 8
  • 60
  • 84
Gordon
  • 312,688
  • 75
  • 539
  • 559
8

You could call get_parent_class repeatedly until it returns 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;
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

If you want to check for specific types, or build a function to create drilldown without using any of the other solutions, you could resort to 'instanceof' to determine if it's a specific type as well, It will be true for checking if a class extends a parent class.

superfro
  • 3,327
  • 1
  • 18
  • 14
0

The ReflectionClass class part of the PHP Reflection API has a getParentClass() method.

Here's a small code sample using it:

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

Alex Jasmin
  • 39,094
  • 7
  • 77
  • 67