클래스 이름이 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'];
}
}
혼합 솔루션을 사용해야합니다. 배열을 생성자에 전달합니다. 생성자에서 배열을 추출하고 개별적으로 변수를 할당합니다. 참조 추출 http://php.net/manual/en/function.extract.php –
'항목'의'name' 메소드를 제외하고 모두 ok입니다. –