Mic*_*lle 0 php variables class
我正在尝试调用一个类函数来创建一个子类的新实例.
我在foreach循环中执行此操作,并为子类名和参数使用以下变量:
$classname = 'Element_Radio';
$classargs = array( $a, $b ); //Might have up to 4 arguments
Run Code Online (Sandbox Code Playgroud)
这是我正在尝试执行的原始代码行,没有任何上述变量:
$form->addElement(new Element_Radio($required, $required, $optional_array, $optional_array);
Run Code Online (Sandbox Code Playgroud)
所以首先我试过:
$form->addElement( new $classname ($classargs) );
Run Code Online (Sandbox Code Playgroud)
但我想我需要这样的东西:
$form->addElement( call_user_func_array(new $classname,$classargs) );
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,我都会遇到以下错误:
"警告:缺少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 ) );
Run Code Online (Sandbox Code Playgroud)
使用参数解包操作符...
:
new $classname(...$classargs)
Run Code Online (Sandbox Code Playgroud)
或反思:
(new ReflectionClass($classname))->newInstanceArgs($classargs)
Run Code Online (Sandbox Code Playgroud)