How to call PHP function from string stored in a V

2018-12-31 14:07发布

I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:

function foo ()
{
  //code here
}

function bar ()
{
  //code here
}

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

Anyhelp would be great.

Thanks!

14条回答
泛滥B
2楼-- · 2018-12-31 15:07

Following code can help to write dynamic function in PHP. now the function name can be dynamically change by variable '$current_page'.

$current_page = 'home_page';
$function = @${$current_page . '_page_versions'};
$function = function() {
    echo 'current page';
};
$function();
查看更多
妖精总统
3楼-- · 2018-12-31 15:08

Complementing the answer of @Chris K if you want to call an object's method, you can call it using a single variable with the help of a closure:

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 posted another example here

查看更多
登录 后发表回答