Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining class hierarchy of an object at runtime

Tags:

php

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?

like image 750
shealtiel Avatar asked Nov 17 '10 21:11

shealtiel


2 Answers

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
)
like image 114
Gordon Avatar answered Oct 23 '22 16:10

Gordon


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;
}
like image 27
Gumbo Avatar answered Oct 23 '22 17:10

Gumbo