Php 将值传递给类构造函数(变量与数组)
我有一个名为Items的类,在实例化时该类应该接收5+个值。 我知道向构造函数传递超过(3-4)个变量表明设计很差 将这个数量的变量传递给构造函数的最佳实践是什么 我的第一个选择:Php 将值传递给类构造函数(变量与数组),php,oop,design-patterns,solid-principles,Php,Oop,Design Patterns,Solid Principles,我有一个名为Items的类,在实例化时该类应该接收5+个值。 我知道向构造函数传递超过(3-4)个变量表明设计很差 将这个数量的变量传递给构造函数的最佳实践是什么 我的第一个选择: class Items { protected $name; protected $description; protected $price; protected $photo; protected $type; public function __constru
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;
}
您拥有良好的体系结构和第一个解决方案。但是,如果您的属性是动态的,并且您不知道它们是什么,那么您可以使用第二种解决方案来实现它。在这种情况下,您可以使用修改后的第二个选项:
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;
}
你应该使用混合溶液。将数组传递给构造函数。在构造函数
中,提取该数组并单独分配变量。在Items
中提取引用除方法name
之外的所有ok。谢谢,我相信这是我能得到的最好的方法,我可以调用$Items->getAttributes()->name,时间复杂度为O(1),而不是每次使用循环。干杯:)