How to call PHP function from string stored in a Variable


Question

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 ()
{
  //code here
}

function bar ()
{
  //code here
}

$functionName = "foo";
// i need to call the function based on what is $functionName

Anyhelp would be great.

Thanks!

1
268
6/29/2010 8:43:24 AM

Accepted Answer

438
5/17/2012 7:31:39 AM

My favorite version is the inline version:

${"variableName"} = 12;

$className->{"propertyName"};
$className->{"methodName"}();

StaticClass::${"propertyName"};
StaticClass::{"methodName"}();

You can place variables or expressions inside the brackets too!


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon