将值传递给 class 构造函数(变量与数组)

Passing values to class constructor (variables vs array)

我有一个 class 命名的项目,在实例化时 class 应该接收 5+ 个值。 我知道将超过 (3-4) 个变量传递给构造函数表示设计不佳。

将这个数量的变量传递给构造函数的最佳做法是什么?

我的第一个选择:

class Items {

    protected $name;
    protected $description;
    protected $price;
    protected $photo;
    protected $type;

    public function __construct($name, $description, $price, $photo, $type)
    {
        $this->name = $name;
        $this->description = $description;
        $this->price = $price;
        $this->photo = $photo;
        $this->type = $type;
    }

    public function name()
    {
        return $this->name;
    }

和第二个选项:

class Items {
    protected $attributes;

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    public function name()
    {
        return $this->attributes['name'];
    }
}

第一个解决方案的架构很好。但是如果您的属性是动态的并且您不知道它们是什么,您可以使用第二种解决方案来实现它。在这种情况下,您可以使用修改后的第二个选项:

class Items {
    protected $attributes;

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    public function getAttributes()
    {
        return $this->attributes;
    }
}

$items = new Items($attributes);

foreach ($items->getAttributes() as $attribute) {
    echo $attribute->name;
}