Determining class hierarchy of an object at runtime

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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
)

Solution 2

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;
}

Solution 3

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.

Solution 4

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply