Variable functions

bool is_callable ( mixed function_name [, bool syntax_only [, string callable_name]])

mixed call_user_func ( callback function [, mixed parameter [, mixed ...]])

mixed call_user_func_array ( callback function [, array parameters])

As you have seen already, PHP has variable variables so it is not surprising we have variable functions. This particular piece of clever functionality allows you to write code like this:

<?php
    $func = "sqrt";
    print $func(49);
?>

PHP sees that you are calling a function using a variable, looks up the value of the variable, then calls the matching function. The code above will therefore return 7 - the square root of 49.

As variable functions are quite unusual and also easy to get wrong, there is a special PHP function, is_callable(), that takes a string as its only parameter and returns true if that string contains a function name that can be called using a variable function. Thus, our script becomes this:

<?php
    $func = "sqrt";
    if (is_callable($func)) {
        print $func(49);
    }
?>

As an alternative to variable functions, you can use call_user_func() and call_user_func_array(), which take the function to call as their first parameter. The difference between the two is that call_user_func() takes the parameters to pass into the variable function as multiple parameters to itself, whereas call_user_func_array() takes an array of parameters as its second parameter.

This next script demonstrates both of these two performing a functionally similar operation, replacing "monkeys" with "giraffes" in a sentence using str_replace():

<?php
    $func = "str_replace";
    $output_single = call_user_func($func, "monkeys", "giraffes", "Hundreds and thousands of monkeys\n");
    $params = array("monkeys", "giraffes", "Hundreds and thousands of monkeys\n");
    $output_array = call_user_func_array($func, $params);
    echo $output_single;
    echo $output_array;
?>

Although call_user_func() is essentially the same as using a variable function, call_user_func_array() is very helpful for functions that have complex and variable parameter requirements. One popular application for variable functions is to allow other developers using your code to register callbacks - they pass in the name of the function they want your code to call, then you can use call_user_func() to execute that.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Callback functions >>

Previous chapter: Recursive functions

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.