【发布时间】:2017-05-18 06:56:33
【问题描述】:
我有一个名为 Items 的类,在实例化时该类应该接收 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'];
}
}
【问题讨论】:
-
您应该使用混合解决方案。将数组传递给构造函数。在构造函数
extract中,该数组并单独分配变量。提取参考php.net/manual/en/function.extract.php -
除了
Items中的方法name之外一切正常。
标签: php oop design-patterns solid-principles