tags:

views:

77

answers:

3

How can I pass a function as a variable and then call it using that variable?

e.g.

test(echo);
function test($function)
{
    $function("Test");
}
+6  A: 

You can just pass the function name as a string and it will work.

Note however that echo is not a function, so this does not work with echo.

Edit: Here's an example:

function my_function($x)
{
    echo $x;
}
function test($function)
{
    $function("Test");
}
test("my_function");
sepp2k
Could you give an example?
jSherz
+3  A: 

You’re already on the right track with variable functions. But echo is a language construct and not a function:

Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Besides that, the function would either be passed by its identifier:

test('function_name');

Or, in case of using anonymous functions, by its value:

test(function() { /* … */ });

You should also take a look at is_callable that can be used to test if the given parameter is callable.

Gumbo
A: 

For a function like, say, substr, you can call a string with the value "substr":

$func = "substr";
$result = $func($string, 0, 10);

Eval can also be used:

$func = "substr";
$result = eval("return $func(\$string, 0, 10);");

Proceed with caution when using either of these. If $func is from user input, a malicious user could execute any function. Since PHP does not care too much (issues a warning) if you specify additional arguments, someone could, for example, execute "exec" with $string equal to "rm -rf /".

You can't do this with echo, because it is not a function; it is a language construct, like "if", or "while".

Thomas O