2017-05-18 1 views
0

클래스 이름이 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']; 
    } 
} 
+0

혼합 솔루션을 사용해야합니다. 배열을 생성자에 전달합니다. 생성자에서 배열을 추출하고 개별적으로 변수를 할당합니다. 참조 추출 http://php.net/manual/en/function.extract.php –

+0

'항목'의'name' 메소드를 제외하고 모두 ok입니다. –

답변

0

당신은 최초의 솔루션 잘 아키텍처를 가지고있다. 그러나 속성이 동적이며 두 번째 솔루션으로 구현할 수있는 기능이 무엇인지 모를 경우 이 경우 수정 된 두 번째 옵션을 사용할 수 있습니다.

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; 
} 
+1

고마워,이게 내가 얻을 수있는 최선이라고 믿는다. 매번 루프를 사용하는 O (n) 대신에 O (1) 시간 복잡성을 가진 $ items-> getAttributes() -> 이름을 부를 수있다. 건배 :) –

관련 문제