【问题标题】:Using variables for name and arguments to create a new instance of a class in PHP [duplicate]使用名称和参数的变量在 PHP 中创建类的新实例 [重复]
【发布时间】: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 ) );

【问题讨论】:

    标签: php class variables


    【解决方案1】:

    要么使用argument unpacking operator ...

    new $classname(...$classargs)
    

    reflection:

    (new ReflectionClass($classname))->newInstanceArgs($classargs)
    

    【讨论】:

    • 变量函数操作符在函数定义中,即参数解包或splat
    • 对了。除了“……token”之外,它似乎并没有真正的官方名称,这使得它有点难以谈论。
    • 我最终为通过搜索到达这里的任何人使用了上面编辑过的代码。
    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2014-05-25
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    相关资源
    最近更新 更多