我有一个名为Item的类,在实例化时,类应该接收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'];
}
}发布于 2017-05-18 07:14:59
您拥有良好的体系结构和第一个解决方案。但是,如果您的属性是动态的,并且您不知道它们是什么,那么可以使用第二个解决方案来实现它。在这种情况下,您可以使用修改后的第二个选项:
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;
}https://stackoverflow.com/questions/44040666
复制相似问题