How to Execute a Function Name String in PHP Programming 29 JUL 2013

green php elephants - elephpantsVariable function execution is a pretty handy trick, particularly if you are not assured that all objects carry the same set of shared functions.

For example you might have two similar objects but with two slightly different associated functions, meaning that when you script is presented with either of these two object, you need to execute the associated function. And while switch case statements work perfectly well for this type of example, they don’t scale up very well, meaning more often than not, it’s easier just to store the function names with the object itself.

The question now is, how do we execute a function given the function name as a string?

Well the answer lies with PHP’s built in call_user_func function that calls the provided callback (string function name), and goes even further by passing any remaining parameters into the callback call as arguments.

In practice:

function test3($message,$strings){
    echo '<p>test 3: ' . $message . '</p>';
    echo '<pre>';
    echo '</pre>';

$function = 'test3';
$message = 'hello 3!';
$options = array('line 1','line 2','line 3');

if (function_exists($function)){


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.