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

function foo ()
{
    //code here
}

function bar ()
{
    //code here
}

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

当前回答

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

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

其他回答

是的,这是可能的:

function foo($msg) {
    echo $msg."<br />";
}
$var1 = "foo";
$var1("testing 1,2,3");

来源:http://www.onlamp.com/pub/a/php/2001/05/17/php_foundations.html?page=2

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

//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);
}

使用call_user_func函数。

如果你在一个对象上下文中试图动态调用一个函数,请尝试如下代码:

$this->{$variable}();

补充@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"

我在这里举了另一个例子