开发者

PHP function parameters from a string

开发者 https://www.devze.com 2023-03-07 03:28 出处:网络
How do I make a truely dynamic function with dynamic parameters call? The documentation and examples I\'ve found all assume you have only 1 parameter. I would like to have multiple parameters, example

How do I make a truely dynamic function with dynamic parameters call? The documentation and examples I've found all assume you have only 1 parameter. I would like to have multiple parameters, example:

class Object {
    function A($p1) {}
    function B($p1,$p2) {}
}

$obj = new Object();
$function = "B";
$params = "'foo', 'me'";

$obj->$function($params);

calling $function = "A" will be fine as $params is treated as a string. I've tried

$obj->$function(explode(',',$params));

for $function="B" but it does not work as explode simply returns a开发者_Go百科n array and thus function B has a missing parameter.

Any idea?


You will need to use call_user_func_array and str_getcsv

call_user_func_array(array($obj, "B"), str_getcsv($params));


You can use the call_user_func_array() function as follows:

call_user_func_array(array($obj, $function), explode(',', $params));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号