| re: Variable parameters to variable class constructor
<comingupslowly@gmail.com> wrote in message
news:1103198422.586102.24770@c13g2000cwb.googlegro ups.com...[color=blue]
> Hi
>
> I have a PHP problem I can't solve.
>
> I'm using variable names as class constructors in a project, a la:
>
> $foo = "ClassName";
> $bar = new $foo();
>
> But what I can't work out is how to pass a variable number of
> parameters to the constructor; call_user_func_array looks good, but I
> don't think that'll work in the same way as 'new'.
>
> So what I'm trying to do is:
>
> $bar = new $foo($a, $b, $c);
>
> Where I'm getting the parameters for the constructor from func_get_args
> and as such, I don't know many parameters there are.
> Any suggestions?
>
> Thanks,
>
> Justin[/color]
Time to use good old eval()
<?
$args = array("first", "second", "third");
extract($args, EXTR_PREFIX_ALL, "arg");
$names = array();
for($i = 0; $i < count($args); $i++) $names[] = "\$arg_$i";
$code = "new $class(" . implode(',', $names) . ")";
eval($code);
?> |