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!
For the sake of completeness, you can also use eval():
However,
call_user_func()
is the proper way.In case someone else is brought here by google because they were trying to use a variable for a method within a class, the below is a code sample which will actually work. None of the above worked for my situation. The key difference is the
&
in the declaration of$c = & new...
and&$c
being passed incall_user_func
.My specific case is when implementing someone's code having to do with colors and two member methods
lighten()
anddarken()
from the csscolor.php class. For whatever reason, I wanted to have the same code be able to call lighten or darken rather than select it out with logic. This may be the result of my stubbornness to not just use if-else or to change the code calling this method.Note that trying anything with
$c->{...}
didn't work. Upon perusing the reader-contributed content at the bottom of php.net's page oncall_user_func
, I was able to piece together the above. Also, note that$params
as an array didn't work for me:This above attempt would give a warning about the method expecting a 2nd argument (percent).
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
A few years late, but this is the best manner now imho:
Dynamic function names and namespaces
Just to add a point about dynamic function names when using namespaces.
If you're using namespaces, the following won't work except if your function is in the global namespace:
What to do?
You have to use
call_user_func()
instead:$functionName()
orcall_user_func($functionName)