Fuxi
Fuxi

Reputation: 7599

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:

$rc = 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

Upvotes: 6

Views: 10643

Answers (6)

AJ.
AJ.

Reputation: 28174

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

Upvotes: 2

Michael
Michael

Reputation: 2631

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

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

Upvotes: 1

Ondřej Mirtes
Ondřej Mirtes

Reputation: 5616

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.

Upvotes: 1

deadalnix
deadalnix

Reputation: 2325

$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.

Upvotes: 2

James C
James C

Reputation: 14149

I think this is what you're after:

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

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

Upvotes: 7

KilZone
KilZone

Reputation: 1615

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.

Upvotes: 1

Related Questions