tags:

views:

33

answers:

2

Hello,

I have classname stored in variable $classname; also I have an array of values I should pass into object constructor.

$classname = "MyClass";
$variables = array(1, 2, 3, 4);

I need

$objInstance = new MyClass(1, 2, 3, 4);

How?

Thank you.

A: 
$objInstance = new $classname($variables[0], $variables[1], $variables[2], $variables[3]);
thetaiko
I'm guessing he doesn't want the list of parameters to be hard-coded like this
Pascal MARTIN
+5  A: 
$r = new ReflectionClass($classname);
$objInstance = $r->newInstanceArgs($variables);
stereofrog
+1 Nicely done ! Didn't think about Reflection -- but, once again, it helps doing what seemed impossible ;-)
Pascal MARTIN
Great solution! Since SPL isn't documented good yet, here is PHP SPL Reflection class description http://www.tuxradar.com/practicalphp/16/4/0
Kirzilla