如何使用内爆将数组中的每个元素传递给对象构造函数


How can you pass each element in an array to an object constructor using implode?

给定一个简单的类:

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和名称被设置为NULL。将数组的值作为参数发送给对象构造函数的正确语法是什么?

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

应该是这样的:

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

对于常规的函数调用,您将使用call_user_func_array,对于实例化类,您将不得不使用反射:

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

在PHP 5.6+中,你可以使用变长参数列表,也就是解包:

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

它工作得很好,但不是你期望的那样。也许你需要接收一个数组

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