30

Possible Duplicate:
Use a variable to define a PHP function

Is there a way of using a variable as a function name.

For example i have a variable

$varibaleA;

and I want to create a function i.e.

function $variableA() {
}

so this function can be called later in the script. Does anyone know if this can be done?

Thanks

Community
  • 1
  • 1
Carl Thomas
  • 3,605
  • 6
  • 38
  • 50
  • why ever you think this is a good idea, theirs probably a better solution. –  Dec 11 '11 at 18:51
  • possible duplicate of [Use a variable to define a PHP function](http://stackoverflow.com/questions/7213825/use-a-variable-to-define-a-php-function) or [PHP: define functions with variable names](http://stackoverflow.com/questions/7337883/php-define-functions-with-variable-names) – mario Dec 11 '11 at 18:52
  • Not a duplicate. That one asks to define a function using *Dynamic* names - not just with a variable. – Ulad Kasach Sep 23 '15 at 16:43
  • BY any chance, do you want to create a dynamic function – Cholthi Paul Ttiopic Feb 10 '18 at 09:47
  • As said by @mario, : `$functionToCall = 'show__personalizer_'.$_GET['page'];`, then `$functionToCall()` – London Smith Nov 20 '18 at 19:54

3 Answers3

32

Declaring a function with a variable but arbitrary name like this is not possible without getting your hands dirty with eval() or include().

I think based on what you're trying to do, you'll want to store an anonymous function in that variable instead (use create_function() if you're not on PHP 5.3+):

$variableA = function() {
    // Do stuff
};

You can still call it as you would any variable function, like so:

$variableA();
hakre
  • 193,403
  • 52
  • 435
  • 836
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
18
$x = 'file_get_contents';
$html = $x('http://google.com');

is functionally equivalent to doing

$html = file_get_contents('http://google.com');

They're called variable functions, and generally should be avoided as they're too far removed from variable variables.

Marc B
  • 356,200
  • 43
  • 426
  • 500
3

you can do this:

$foo = function() {
    //..
};

and then:

$foo(); 

works in PHP 5.3+

Kakashi
  • 2,165
  • 14
  • 19