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:
new Class(${$a[0]});
break;
case 2:
new Class(${$a[0]}, ${$a[1]});
break;
etc...
There has to be a better way to do this. If I have an array of strings ("variable1", "variable2", 'variable3", ...), how can I instantiate a Class without manually accounting for every possibility?
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
}
}
}
// 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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With