【问题标题】:How can you pass each element in an array to an object constructor using implode?如何使用 implode 将数组中的每个元素传递给对象构造函数?
【发布时间】:2015-11-29 11:13:19
【问题描述】:

给定一个简单的类:

class Foo {
    public $id;
    public $name;
    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}

尝试通过内爆值数组来实例化类失败:

$params = array(2,'TestFoo2');
$baz = new Foo(implode(",", $params)); // doesn't work

整个内爆数组字符串被传递到第一个字段 id 中,并且 name 设置为 NULL。将数组的值作为参数发送给对象构造函数的正确语法是什么?

【问题讨论】:

    标签: php arrays oop constructor


    【解决方案1】:

    您为构造函数提供了错误数量的参数。 Implode 返回单个字符串值,它是数组中元素的串联。

    应该是这样的:

     $baz = new Foo($params[0], $params[1]);
    

    【讨论】:

    • 是的,就像我说的那样;)
    【解决方案2】:

    它运行良好,但没有如您预期的那样。也许你需要以数组的形式接收

    public function __construct($array)
    {
        $this->id = $array['id'] ;
        $this->name = $array['name'] ;
    }
    $params = array("id"=>2, "name" =>'TestFoo2');
    $baz = new Foo( $params); 
    

    【讨论】:

    • 为什么要投反对票?我正确回答了 OP 问题。 What is the correct syntax to send the values of an array as parameters to an object constructor?
    • 我没有DV,但我问如何发送数组的值。您的解决方案是发送实际的数组。
    • 你不能按照你试图做的方式去做。 eval 有一个解决方案,但出于安全原因,您不能使用它。如果你有一个参数数组,你需要手动传递它们new Foo($array[0], $array[1])
    • 好吧,我不知道。很好的解决方案
    【解决方案3】:

    对于常规函数调用,您将使用 call_user_func_array,对于实例化类,您必须使用 reflection

    $baz = (new ReflectionClass('Foo'))->newInstanceArgs($params);
    

    在 PHP 5.6+ 中,您可以使用 variable-length argument lists,也就是解包:

    $baz = new Foo(...$params);
    

    【讨论】:

    • 可变长度参数列表完美运行。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 2020-07-27
    • 1970-01-01
    • 2018-08-04
    • 2014-06-04
    • 1970-01-01
    • 2012-03-14
    • 2010-11-17
    相关资源
    最近更新 更多