John Doe
John Doe

Reputation: 23

Function name inside a variable

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.

Upvotes: 0

Views: 328

Answers (4)

user97410
user97410

Reputation: 724

You can also do sprintf($string).

Upvotes: -1

artlung
artlung

Reputation: 33833

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()

Upvotes: 2

Byron Whitlock
Byron Whitlock

Reputation: 53921

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

Upvotes: 3

cletus
cletus

Reputation: 625427

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).

Upvotes: 2

Related Questions