By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,968 Members | 1,843 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,968 IT Pros & Developers. It's quick & easy.

Variable parameters to variable class constructor

P: n/a
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

Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
co************@gmail.com wrote:
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?


http://www..php.net/manual/en/functi...c-num-args.php
JW

Jul 17 '05 #2

P: n/a
<co************@gmail.com> wrote in message
news:11*********************@c13g2000cwb.googlegro ups.com...
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


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

?>
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.