Get class hierarchy in PHP

function walk_up_hierarchy($object,$method) {
    $values = array();
    $class = get_class($object);
    do {
        array_unshift($values,$class::$method());
    } while (($class = get_parent_class($class)) !== false);
    return $values;
}

Get class hierarchy in PHP: The snippet’s story

Yesterday I tried to call a function for every parent class of an object and get the results in an array. I didn’t find the solution instantly, so I thought that’s something for the snippets section.

The function above takes an instance of a class and a class method’s name. Then it calls the function on the object, storing the result as an array-item. Next it calls the method of the parent class of the object, storing the result in the beginning of the result-array and so on.

Apparently the method has to be defined in all parent classes, if that is not guaranteed you have to take further precautions.

Tagged with:

Archived comments

Comments are archived. New comments are not available on this archived article.