I'm trying to call a class function that creates a new instance of a subclass.
I'm doing this inside a foreach loop with the following variables for the sub class name and arguments:
$classname = 'Element_Radio';
$classargs = array( $a, $b ); //Might have up to 4 arguments
Here's the original line of code I'm trying to execute, without any of the above variables:
$form->addElement(new Element_Radio($required, $required, $optional_array, $optional_array);
So first I tried:
$form->addElement( new $classname ($classargs) );
But I think I need something like this:
$form->addElement( call_user_func_array(new $classname,$classargs) );
Either way, I'm getting errors of:
"Warning: Missing argument 2 for Element::__construct() ..."
So it looks like the arguments are getting passed in as one array variable, and not separately.
I ended up writing a bunch of if statements to just make the function call depending on the values of $classargs, but I'm wondering if there is a programmatic way of doing what I want without the IFs.
EDIT - SOLUTION with the code I added to account for the fact that my array of arguments was a multidimensional array that didn't have all numeric indexes. The splat operator (...) only works with an array with numeric indexes.
$classname = 'Element_Radio';
$classargs = array();
if ( isset( $a ) ) { array_push($classargs, $a); }
if ( isset( $b ) ) { array_push($classargs, $b); }
if ( isset( $c ) ) { array_push($classargs, $c); }
if ( isset( $d ) ) { array_push($classargs, $d); }
$form->addElement( new $classname ( ...$classargs ) );