I need to pass a variable number of strings to instantiate different classes. I can always do a switch on the size of the array:
switch(count($a)) {
case 1:
// Constructs an instance of a class with a variable number of parameters.
function make() { // Params: classname, list of constructor params
$args = func_get_args();
$classname = array_shift($args);
$reflection = new ReflectionClass($classname);
return $reflection->newInstanceArgs($args);
}
How to use:
$MyClass = make('MyClass', $string1, $string2, $string3);
Edit: if you want to use this function with your $a = array("variable1", "variable2", 'variable3", ...)
call_user_func_array('make', array_merge(array('MyClass'), $a));
If you must do it this way, you can try:
$variable1 = 1;
$variable2 = 2;
$variable3 = 3;
$variable4 = 4;
$varNames = array('variable1', 'variable2', 'variable3', 'variable4');
$reflection = new ReflectionClass('A');
$myObject = $reflection->newInstanceArgs(compact($varNames));
class A
{
function A()
{
print_r(func_get_args());
}
}
<?php
new Example($array);
class Example
{
public function __construct()
{
foreach (func_get_args() as $arg)
{
// do stuff
}
}
}
Look here. Does method 2 help ? Also, perhaps by moving the switch to the constructor (if that is practical) you would be able to hide this from the rest of the code.
have a look at the factory design pattern:
class Factory {
public static function CreateInstance($args) {
switch(func_get_num_args()) {
case …:
return new ClassA(…); break;
case …:
return new ClassB(…); break;
}
}
}
It seems that reflection can pull this one out of the hat for you. This comes to you courtesy of the PHP call_user_func_array notes. The following code will create a class by calling the constructor with the contents of your array.
<?php
// arguments you wish to pass to constructor of new object
$args = array('a', 'b');
// class name of new object
$className = 'ClassName';
// make a reflection object
$reflectionObj = new ReflectionClass($className);
// use Reflection to create a new instance, using the $args
$command = $reflectionObj->newInstanceArgs($args);
// this is the same as: new myCommand('a', 'b');
?>