【发布时间】:2017-03-09 20:01:42
【问题描述】:
我正在尝试调用创建子类的新实例的类函数。
我在 foreach 循环中使用以下变量作为子类名称和参数:
$classname = 'Element_Radio';
$classargs = array( $a, $b ); //Might have up to 4 arguments
这是我尝试执行的原始代码行,没有任何上述变量:
$form->addElement(new Element_Radio($required, $required, $optional_array, $optional_array);
所以我首先尝试了:
$form->addElement( new $classname ($classargs) );
但我想我需要这样的东西:
$form->addElement( call_user_func_array(new $classname,$classargs) );
无论哪种方式,我都会遇到以下错误:
“警告:缺少 Element::__construct() 的参数 2 ...”
所以看起来参数是作为一个数组变量传入的,而不是单独传入的。
我最终编写了一堆 if 语句来根据 $classargs 的值进行函数调用,但我想知道是否有一种编程方式可以在没有 IF 的情况下执行我想要的操作。
编辑 - 使用我添加的代码的解决方案,以说明我的参数数组是一个没有所有数字索引的多维数组。 splat 运算符 (...) 仅适用于具有数字索引的数组。
$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 ) );
【问题讨论】: