6

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.

Question Mark
  • 3,557
  • 1
  • 25
  • 30
  • 1
    possible duplicate of [php: determining class hierarchy of an object at runtime](http://stackoverflow.com/questions/4209201/php-determining-class-hierarchy-of-an-object-at-runtime) – Gordon Apr 12 '11 at 20:01

3 Answers3

13

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.

Christopher Manning
  • 4,527
  • 2
  • 27
  • 36
9

After being pointed to the duplicate question i have gone for:

function get_class_lineage($object){
    $class_name = get_class($object);
    $parents = array_values(class_parents($class_name));
    return array_merge(array($class_name), $parents);
}

The class_parents function from the standard library was the obvious thing i was overlooking.

I thought Reflection was overkill for this simple task.

Question Mark
  • 3,557
  • 1
  • 25
  • 30
2

As you can read at manual you can also give a classname as a string to the function.

$class = get_class($this);
$lineage = array();
do {
  $lineage[] = $class;
  $class = get_parent_class($class);
} while ($class != 'stdClass');

Here index 0 is the classname of the object itself:

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • Not so hurting by now, I guess, but string classname requires PHP >= 5.1.0 – Niki Romagnoli Jul 21 '20 at 15:24
  • 1
    Well, PHP 5.6 is not supported since 2018. So if one is using a version < 7.2 (current version, security fixes only), they have other problems, than string classnames. (For the curious ones: 5.0 had its EOL on 5 Sep 2005). – KingCrunch Jul 23 '20 at 16:30