Calling functions with variable functions I have some PHP code where I use variable functions to call the right function. I need to build a chart array (for example), and the chart array that comes out has a fixed format. But the data that goes into the chart or table comes from varying places in the underlying objects.

An example:

private function buildChartGroups(PropelCollection $groups, $propertyForDisplay) {
    $groupDisplayFunction = "getSum$propertyForDisplay";

    $chart = array();
    foreach ($groups as $group) {
            $chart[] = array('name' =&gt; $group-&gt;getName(), 
                             'y' =&gt; $group-&gt;$groupDisplayFunction()
                       );
        }
    }
    return $chart;
}


and then the function gets called something like:

$result = $this-&gt;buildChartGroups($groups, "Total");
...elsewhere...
$result = $this-&gt;buildChartGroups($groups, "Count");


where $groups is an array of Group objects:

class Group {
   private $name;
   private $sumTotal;
   private $sumCount;

   public function getName() {
       return $this-&gt;name;
   }

   public function getSumTotal() {
        return $this-&gt;sumTotal;  
   }

   public function getSumCount() {
        return $this-&gt;sumCount;
   }
}


This works fine and lets me re-use buildChartGroups() which I would otherwise not be able to do. But using variable functions and passing function names as strings always seems a little dirty, even though I'm sure it has its place.

Is there a way to refactor this or is there some pattern I can use to avoid them?
I agree, it does feel dirty to compute the function name like that.

A typical way to do dynamic dispatching is using polymorphism.  You could formalize the mechanism for determining which function to call by making some property-extracting objects:

abstract class PropertyExtractor {
    public abstract function getProperty($group);
}

class SumTotalExtractor extends PropertyExtractor {
    public function getProperty($group) {
        return $group-&gt;getSumTotal();
    }
}

class SumCountExtractor extends PropertyExtractor {
    public function getProperty($group) {
        return $group-&gt;getSumCount();
    }
}




Your buildChartGroups() would take one of those extractors as the second parameter:

private function buildChartGroups(PropelCollection $groups, $propertyExtractor) {
    $chart = array();
    foreach ($groups as $group) {
        $chart[] = array('name' =&gt; $group-&gt;getName(), 
                         'y' =&gt; $propertyExtractor-&gt;getProperty($group));
    }
    return $chart;
}




Here it is in use:

$result = $this-&gt;buildChartGroups($groups, new SumTotalExtractor());