views:

4254

answers:

7

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 ()
{
  //code here
}

function bar ()
{
  //code here
}

$functionName = "foo";
// i need to call the function based on what is $functionName

Anyhelp would be great.

Thanks!

+2  A: 

The correct answer is, yes, it is possible:

function foo($msg) {
    echo $msg."<br />";
  }
  $var1 = "foo";
  $var1("testing 1,2,3");

Source: http://www.onlamp.com/pub/a/php/2001/05/17/php_foundations.html?page=2

Sev
A: 

Use the call_user_func function.

Visage
+13  A: 

$functionName() or call_user_func($functionName)

knittl
Thanks this is great!
Lizard
I need to do this myself but I'm kind of unsettled that it's so easy (to abuse) :D
andyjdavis
+1, even if I don't personnaly recommand $functionName(), harder to read and detect.
Clement Herreman
A: 

I dont know why u have to use that, doesnt sound so good to me at all, but if there are only a small amount of functions, you could use a if/elseif construct. I dont know if a direct solution is possible.

something like $foo = "bar"; $test = "foo"; echo $$test;

should return bar, you can try around but i dont think this will work for functions

Flo
+2  A: 

For the sake of completeness, you can also use eval():

$functionName = "foo()";
eval($functionName);

However, call_user_func() is the proper way.

karim79
A: 

Trying to code that way is going to make that project/code very hard to maintain in the long run and it will make it more of a headache then is needed. i don't know why you can't just call the function name, it would be just as easy to do as any of the methods described above. +1 to both code samples for the two simplest answers ever :)

Marc Towler
+1  A: 

The manual is pretty clear in this case imo.

anddoutoi