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.

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I need to call function like $this->function_name how can I do that?
That also works, with a little modification. $this->$functionName();
Sorry! to ask stupid question but It emergency for my project. anyway It work fine. Thanks
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 :)
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.

1 Comment

I need to call function like $this->function_name how can I do that?
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));

1 Comment

I need to call function like $this->function_name how can I do that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.