views:

178

answers:

1

I have an array of reflectionClasses.

I need to get a reflectionObject from one of these and then call its constructor with some parameters.

The point is to instantiate an object without knowing the class name (i'll know it at runtime).

Example, just to render the idea:

foreach (Conf::get_array() as $reflection_class) {
     //it's not right, just to render the idea
     $reflectionObject = new ReflectionObject ($reflection_class); 
     $objects[] = $reflectionObject->construct($param_1, $param_2); 
}

Another example:

foreach (Conf::get_array() as $reflection_class) {
     $objects[] = new $reflection_class($param_1, $param_2); //not right. maybe from php 5.3?
}
+2  A: 

You don't need an instance of ReflectionObject for that. ReflectionClass has the two methods

public stdclass newInstance(mixed args)
public stdclass newInstanceArgs(array args)

example:

<?php
class Foo {
  public function __construct($a, $b) { echo "Foo($a,$b) "; }  
}
class Bar {
  public function __construct($a, $b)  { echo "Bar($a,$b) "; }  
}

class Conf {
  public static function get_array() {
    return array(new ReflectionClass('Foo'), new ReflectionClass('Bar'));
  }
}



$args = array('A', 'B');
$object = array();
foreach (Conf::get_array() as $reflection_class) {
  $objects[] = $reflection_class->newInstanceArgs($args);
}

var_dump($objects);
VolkerK
great answer! that's exactly what i was seeking, but documentation was not so clear
avastreg