views:

73

answers:

4

Hello. I have a simple question (i guess). I'm getting the name of the function inside a variable from database. After that, i want to run the specific function. How can i echo the function's name inside the php file? The code is something like this:

$variable= get_specific_option;
//execute function
$variable_somesuffix();

The "somesuffix" will be a simple text. I tried all the things i had in mind but nothing worked.

+2  A: 

You want call_user_func

 function hello($name="world")
 {
     echo "hello $name";
 }

$func = "hello";

//execute function
call_user_func($func);
> hello world

call_user_func($func, "byron");
> hello byron
Byron Whitlock
+2  A: 

There are two ways you can do this. Assuming:

function foo_1() {
  echo "foo 1\n";
}

You can use call_user_func():

$var = 'foo';
call_user_func($foo . '_1');

or do this:

$var = 'foo';
$func = $var . '_1';
$func();

Unfortunately you can't do the last one directly (ie ($var . '_1')(); is a syntax error).

cletus
+2  A: 

You want variable variables.

Here's some sample code to show you how it works, and the errors produced:

function get_specific_option() {
    return 'fakeFunctionName';
}

$variable = get_specific_option();

$variable();
// Fatal error: Call to undefined function fakeFunctionName()

$test = $variable . '_somesuffix';

$test();
// Fatal error: Call to undefined function fakeFunctionName_somesuffix()
artlung
Thank you very much.
John Doe
A: 

You can also do sprintf($string).