我需要能够调用一个函数,但函数名存储在一个变量,这是可能的吗?例句:

function foo ()
{
    //code here
}

function bar ()
{
    //code here
}

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

当前回答

使用call_user_func函数。

其他回答

为了完整起见,你也可以使用eval():

$functionName = "foo()";
eval($functionName);

然而,call_user_func()是正确的方法。

下面的代码有助于用PHP编写动态函数。 现在函数名可以通过变量'$current_page'动态更改。

$current_page = 'home_page';
$function = @${$current_page . '_page_versions'};
$function = function() {
    echo 'current page';
};
$function();

补充@Chris K的回答,如果你想调用一个对象的方法,你可以在闭包的帮助下使用一个变量来调用它:

function get_method($object, $method){
    return function() use($object, $method){
        $args = func_get_args();
        return call_user_func_array(array($object, $method), $args);           
    };
}

class test{        

    function echo_this($text){
        echo $text;
    }
}

$test = new test();
$echo = get_method($test, 'echo_this');
$echo('Hello');  //Output is "Hello"

我在这里举了另一个例子

使用存储在变量中的名称安全地调用函数的最简单方法是,

//I want to call method deploy that is stored in functionname 
$functionname = 'deploy';

$retVal = {$functionname}('parameters');

我使用如下方法在Laravel中动态创建迁移表,

foreach(App\Test::$columns as $name => $column){
        $table->{$column[0]}($name);
}

如果有人被谷歌带到这里,因为他们试图在一个类中使用一个方法的变量,下面是一个实际工作的代码示例。以上这些方法都不适用于我的情况。关键的区别在于$c = & new…&$c在call_user_func中传递。

我的具体情况是当实现某人的代码必须与颜色和两个成员方法点亮()和暗()从csscolor.php类。不管出于什么原因,我希望有相同的代码能够调用变亮或变暗,而不是用逻辑选择它。这可能是我固执地不使用if-else或更改调用此方法的代码的结果。

$lightdark="lighten"; // or optionally can be darken
$color="fcc";   // a hex color
$percent=0.15;  
include_once("csscolor.php");
$c = & new CSS_Color($color);
$rtn=call_user_func( array(&$c,$lightdark),$color,$percent);

注意,尝试使用$c->{…不管用。通过阅读php.net页面底部call_user_func上的读者提供的内容,我能够将上述内容拼凑在一起。另外,请注意$params作为数组对我不起作用:

// This doesn't work:
$params=Array($color,$percent);
$rtn=call_user_func( array(&$c,$lightdark),$params);

上述尝试将给出关于该方法期望第二个参数(percent)的警告。