0

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.

John Doe
  • 23
  • 4
  • I don't understand what you're asking... – Alix Axel May 03 '10 at 23:53
  • Duplicate of http://stackoverflow.com/questions/1777820/php-variable-in-a-function-name. See also: http://stackoverflow.com/questions/1005857/how-to-call-php-function-from-string-stored-in-a-variable – outis May 03 '10 at 23:56

4 Answers4

3

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
  • 52,691
  • 28
  • 123
  • 168
2

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
  • 616,129
  • 168
  • 910
  • 942
2

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
  • 33,305
  • 16
  • 69
  • 121
-1

You can also do sprintf($string).

user97410
  • 714
  • 1
  • 6
  • 22