您可以使用此函数查找多个对象或类的共同父类。
<?php
function get_first_common_parent($objects) {
$common_ancestors = null;
foreach($objects as $object) {
if (is_object($object)) {
$class_name = get_class($object);
} else {
$class_name = $object;
}
$parent_class_names = array();
$parent_class_name = $class_name;
do {
$parent_class_names[] = $parent_class_name;
} while($parent_class_name = get_parent_class($parent_class_name));
if ($common_ancestors === null) {
$common_ancestors = $parent_class_names;
} else {
$common_ancestors = array_intersect($common_ancestors, $parent_class_names);
}
}
return reset($common_ancestors);
}
?>
例子
<?php
类 A {
}
类 B 扩展 A {
}
类 D 扩展 B {
}
类 E 扩展 B {
}
类 C 扩展 A {
}
类 F 扩展 C {
}
类 G 扩展 F {
}
类 H {
}
get_first_common_parent(array('G', 'E'));
get_first_common_parent(array(new G(), 'F'));
get_first_common_parent(array('C', 'H'));
get_first_common_parent(array(new B(), 'X'));
?>