Reputation: 21
I am dynamically instantiating objects within another class using an array of strings, but I am getting errors (presumably from the autoloader). Ex:
$inputs=array('class1(1,5)','class2('a','b'));
$objectArray=array();
foreach($inputs as $input)
$objectArray[]=new $input;
I am instantiating an array of objects using an array of strings with the declarations. I believe this is causing incorrect references in my autoloader, does anyone have any insight into this? Thanks!
Upvotes: 1
Views: 369
Reputation: 131881
First of all, you should consider using an existing Dependency Injection Container implementation.
However, you want to instantiate the class with constructor arguments, what makes this slightly more complex. In fact you have to use Reflection
:
For example:
$inputs = array(array('class'=>'class1','arguments'=>array(1,5)));
foreach ($inputs as $description) {
$refClass = new ReflectionClass($description['class']);
$objectArray[] = $refClass->newInstanceArgs($description['arguments']);
}
ReflectionClass::newInstanceArgs()
Upvotes: 2
Reputation: 51411
In this block,
foreach($inputs as $input)
$objectArray[]=new $input;
$input
is intended to be a string containing the class name you're instantiating.
Instead, you're passing wacky things like "class1(1,5)", which are most certainly not just the class names.
If you need to pass arguments to the constructor, you need to do so separately. For example,
foreach($inputs as $input)
$objectArray[]=new $input(1,5);
would work as you expect.
Therefore, you need to split your class names from your constructor parameters. Unfortunately this can get a bit messy. Unless you'll always and only have two arguments to all of the classes, you may find yourself in trouble.
You'll probably find yourself needing to use ReflectionClass::newInstanceArgs
to create a new instance of a class and provide an array of arguments. Modifying the example invocation from the manual page:
foreach($inputs as $input) {
$class = new ReflectionClass($input);
$objectArray[] = $class->newInstanceArgs(array(1, 5));
}
Upvotes: 2