0
votes

I found question from here. But I need to call function name with argument. I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:

function foo ($argument)
{
  //code here
}

function bar ($argument)
{
  //code here
}

$functionName = "foo";
$functionName($argument);//Call here foo function with argument
// i need to call the function based on what is $functionName

Anyhelp would be appreciate.

3

3 Answers

2
votes

Wow one doesn't expect such a question from a user with 4 golds. Your code already works

<?php

function foo ($argument)
{
  echo $argument;
}

function bar ($argument)
{
  //code here
}

$functionName = "foo";
$argument="Joke";
$functionName($argument); // works already, might as well have tried :)

?>

Output

Joke

Fiddle

Now on to a bit of theory, such functions are called Variable Functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

2
votes

If you want to call a function dynamically with argument then you can try like this :

function foo ($argument)
{
  //code here
}

call_user_func('foo', "argument"); // php library funtion

Hope it helps you.

2
votes

you can use the php function call_user_func.

function foo($argument)
{
    echo $argument;
}

$functionName = "foo";
$argument = "bar";
call_user_func($functionName, $argument);

if you are in a class, you can use call_user_func_array:

//pass as first parameter an array with the object, in this case the class itself ($this) and the function name
call_user_func_array(array($this, $functionName), array($argument1, $argument2));