Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a PHP object's ancestors in the inheritance tree

I have an object and want to list all parent classes up until stdClass or whatever.

I have added a polymorphic field to my database table (say categories) and want to automate my finder method so that super classes are also returned, this way i can jump into the inheritance tree at a point i know not necessarily the final subclass:

FoodCategory::find_by_id(10) === Category::find_by_id(10)

SELECT * FROM categories WHERE ..... AND type IN ('FoodCategory', 'Category');

Roughly i guess:

function get_class_lineage($object){
    $class = get_parent_class($object);
    $lineage = array();
    while($class != 'stdClass'){
        $dummy_object = new $class();
        $lineage[] = $class = get_parent_class($dummy_object);
    }

    return $lineage;
}

But this instantiates an object, does anyone know how to achieve this without?

Thanks for any input, i feel like i'm missing something obvious here.

like image 421
Question Mark Avatar asked Apr 12 '11 19:04

Question Mark


1 Answers

Using Reflection

$class = new ReflectionClass($object);

$lineage = array();

while ($class = $class->getParentClass()) {
    $lineage[] = $class->getName();
}

echo "Lineage: " . implode(", ", $lineage);

ReflectionClass accepts either the name of the class or an object.

like image 199
Christopher Manning Avatar answered Oct 21 '22 00:10

Christopher Manning