0

I found question from here. But I need to call function name with argument. 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 ($argument)
{
  //code here
}

function bar ($argument)
{
  //code here
}

$functionName = "foo";
$functionName($argument);//Call here foo function with argument
// i need to call the function based on what is $functionName

Anyhelp would be appreciate.

Community
  • 1
  • 1
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122

3 Answers3

2

Wow one doesn't expect such a question from a user with 4 golds. Your code already works

<?php

function foo ($argument)
{
  echo $argument;
}

function bar ($argument)
{
  //code here
}

$functionName = "foo";
$argument="Joke";
$functionName($argument); // works already, might as well have tried :)

?>

Output

Joke

Fiddle

Now on to a bit of theory, such functions are called Variable Functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • I need to call function like `$this->function_name` how can I do that? – Sadikhasan Mar 18 '15 at 06:55
  • That also works, with a little modification. `$this->$functionName();` – Hanky Panky Mar 18 '15 at 06:56
  • Sorry! to ask stupid question but It emergency for my project. anyway It work fine. Thanks – Sadikhasan Mar 18 '15 at 06:58
  • 1
    The question itself is not stupid, its a good question. But what's really not so cool about is is the fact that you have already written working code and instead of trying it you went ahead and asked others to run it :) – Hanky Panky Mar 18 '15 at 06:59
2

If you want to call a function dynamically with argument then you can try like this :

function foo ($argument)
{
  //code here
}

call_user_func('foo', "argument"); // php library funtion

Hope it helps you.

Jenis Patel
  • 1,617
  • 1
  • 13
  • 20
2

you can use the php function call_user_func.

function foo($argument)
{
    echo $argument;
}

$functionName = "foo";
$argument = "bar";
call_user_func($functionName, $argument);

if you are in a class, you can use call_user_func_array:

//pass as first parameter an array with the object, in this case the class itself ($this) and the function name
call_user_func_array(array($this, $functionName), array($argument1, $argument2));
Raphael Müller
  • 2,180
  • 2
  • 15
  • 20