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 snippets 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 found 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-methods 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 sure you have to take further precautions.