开发者

calling php function from string (with parameters)

i'd like to run a php-function dynamically by using this string:

do_lightbox('image1.jpg', 'picture 1')

i've parsed the string like this:

$exe = "do_lightbox";
$pars = "'image1.jpg', 'picture 1'";

and tried using the following code:

$开发者_StackOverflowrc = call_user_func($exe, $pars);

unfortunately this gives me an error - i've also tried splitting the $pars like

$pars = explode(',', $pars);

but didn't help ..

any ideas? thanks


I think this is what you're after:

$exe = "do_lightbox";
$pars = array('image1.jpg', 'picture 1');

$rc = call_user_func_array($exe, $pars);


$pars must be an array with parameters in it. Should be : array('image1.jpg', 'picture 1') but with your method, it is : array("'image1.jpg'", " 'picture 1'") which isn't what you are looking for.


This is an example of how call_user_func() works:

function myfunc($p1,$p2){
    echo "first: $p1, second: $p2\n";
}

$a1="someval";
$a2="someotherval";
call_user_func("myfunc",$a1,$a2);

The difference here from previous examples it that you don't have to pass each argument in a single array. Also, you can parse an array of delimited strings and do the same thing:

function myfunc($p1,$p2){
    echo "first: $p1, second: $p2\n";
}

$a="someval, someotherval";
$e=explode(", ",$a);
$a1=$e[0];
$a2=$e[1];
call_user_func("myfunc",$a1,$a2);


Best to use call_user_func_array which allows you to pass arguments like an array:

call_user_func_array($exe, $pars);

Alternatively you can use eval to directly parse a string (but I do not recommend this):

eval("do_lightbox('image1.jpg', 'picture 1')");

Which will execute your function.


Although I wonder why do you need such functionality (security problems), here is a solution:

$exe = "do_lightbox";
$pars = "'image1.jpg', 'picture 1'";
call_user_func_array($exe, explode(',', $pars));

You may also want to get rid of the single quotes and spaces around image filenames.


All though it is strongly discouraged you can use the eval function:

eval("do_lightbox('image1.jpg', 'picture 1')")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜