get_class()
will give me the eventual class of an object.
I want t开发者_开发百科o know all the chain of parent classes. How can this be done?
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
)
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;
}
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.
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
精彩评论