在PHP中使用变量作为函数名[重复]

问题描述:

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

可能重复: strong>
使用变量来定义PHP函数 p> blockquote>

有没有办法将变量用作函数名。 p>

例如我有一个变量 p> \ n

  $ varibaleA; 
  code>  pre> 
 
 

我想创建一个函数,即 p>

 函数 $ variableA(){
} 
  code>  pre> 
 
 

因此可以在脚本中稍后调用此函数。 有谁知道这是否可以做到? p>

谢谢 p> div>

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

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

you can do this:

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

and then:

$foo(); 

works in PHP 5.3+