Use Variable as Function Name in PHP

43,562

Solution 1

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();

Solution 2

$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.

Solution 3

you can do this:

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

and then:

$foo(); 

works in PHP 5.3+

Share:
43,562
Carl Thomas
Author by

Carl Thomas

Updated on July 17, 2022

Comments

  • Carl Thomas
    Carl Thomas almost 2 years

    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