0

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 ) );
0

1 Answer 1

5

Either use the argument unpacking operator ...:

new $classname(...$classargs)

Or reflection:

(new ReflectionClass($classname))->newInstanceArgs($classargs)
Sign up to request clarification or add additional context in comments.

3 Comments

variadic function operator is in the function definition, that is argument unpacking or splat
Ah right. It doesn't really seem to have an official name besides "... token", which makes it a bit hard to talk about.
I ended up using the edited code above for anyone who gets here via search.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.