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.

$assoc_arr = array_reduce($arr, function ($result, $item) {
    $result[$item['text']] = $item['id'];
    return $result;
}, array());

The snippets story

I just ran into a problem using array_map on associative arrays, like the following one:

$arr = array(
   array(
      'id' => 22,
      'text' => 'Lorem'
   ),
   array(
      'id' => 25,
      'text' => 'ipsum'
   ),
);

From this array, I wanted to create another, associative array, with the following structure:

$assoc_arr = array(
   'Lorem' => 22,
   'ipsum' => 25
);

My first guess was the array_map function, but I had to realize that there is no way to manipulate the keys of the resulting array. After some googling, I discovered, that it is array_reduce you have to use to simulate array_map on associative arrays.

ps: I know, a simple foreach would have done the trick, but once on the path of functional programming, I didn’t want to leave it that fast 🙂