You can use this function to find common parent of multiple objects or classes.
<?php
/**
* Returns name of the first (in class hierarchy) common parent class of all provided objects or classes.
* Returns FALSE when common class is not found.
*
* @param mixed $objects Array that can contain objects or class names.
* @return mixed
*/
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);
}
?>
Example:
<?php
class A {
}
class B extends A {
}
class D extends B {
}
class E extends B {
}
class C extends A {
}
class F extends C {
}
class G extends F {
}
class H {
}
//returns "A"
get_first_common_parent(array('G', 'E'));
//returns "F"
get_first_common_parent(array(new G(), 'F'));
//returns false (no common parent)
get_first_common_parent(array('C', 'H'));
//returns false (non-existent class provided)
get_first_common_parent(array(new B(), 'X'));
?>