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

5
  • why ever you think this is a good idea, theirs probably a better solution. Commented Dec 11, 2011 at 18:51
  • possible duplicate of Use a variable to define a PHP function or PHP: define functions with variable names Commented Dec 11, 2011 at 18:52
  • Not a duplicate. That one asks to define a function using Dynamic names - not just with a variable. Commented Sep 23, 2015 at 16:43
  • BY any chance, do you want to create a dynamic function Commented Feb 10, 2018 at 9:47
  • As said by @mario, : $functionToCall = 'show__personalizer_'.$_GET['page'];, then $functionToCall() Commented Nov 20, 2018 at 19:54

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Save yourself the nuisance. Note the ; after the }.
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.

Comments

3

you can do this:

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

and then:

$foo(); 

works in PHP 5.3+

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.