Norman
Norman

Reputation: 6365

Concat a variable to a function name

How can I concatenate a variable containing a string to a function name? I tried all methods, but none worked for me.

$mode = 'Remove';

friend.$mode.($mode);

function friendRemove() {

}

Upvotes: 0

Views: 3832

Answers (2)

u_mulder
u_mulder

Reputation: 54841

$function_name = 'friendRemove';
// or
$mode = 'Remove';
$function_name = 'friend' . $mode;

$function_name();

Upvotes: 2

DarkSide
DarkSide

Reputation: 3709

You can use call_user_func https://www.php.net/call_user_func like this:

$mode = 'Remove';
call_user_func('friend'.$mode, $p1, $p2, ...);

function friendRemove($p1, $p2, ...) {}

Also there is call_user_func_array function which is very useful too https://www.php.net/call_user_func_array

Upvotes: 5

Related Questions