2011-11-09 2 views
0

"Place", "Person", "Action"의 오브젝트가 있다고 가정 해 봅시다.오브젝트 구성에서 데이터 가져 오기

사람이있는 장소와이 사람의 나이에 따라이 사람은 다른 행동을 취할 수 있습니다. 예를 들어

:

$place->person->action->drive(); // OK if place is "parking" and "person" is 18+ 
$place->person->action->learn(); // OK if the place is "school" and person is less than 18. 

어떻게 동작 클래스의 객체 "사람"과 "장소"에 대한 데이터를 액세스 할 수 있습니까?

클래스 예 :

class Place { 
    public $person; 
    private $name; 

    function __construct($place, $person) { 
     $this->name = $place; 
     $this->person = $person; 
    } 

} 

class Person { 
    public $action; 
    private $name; 
    private $age; 

    function __construct($name, $age) { 
     $this->name = $name; 
     $this->age = $age; 
     $this->action = new Action(); 
    } 
} 

class Action { 
    public function drive() { 
     // How can I access the person's Age ? 
     // How can I acess the place Name ? 
    } 

    public function learn() { 
     // ... Same problem. 
    } 
} 

은 내가 전송할 수있을 것 "$이"사람의 행동에 내가 작업 개체를 생성 (. 즉, $ this-> 조치를 = 새로운 액션 ($이)) 하지만 장소 데이터는 어떻게됩니까?

답변

0

사람을 장소 또는 행동의 속성을 사람의 속성으로 만드는 것은 이치에 맞지 않습니다.

나는 대중 만들 경향 것 게터 사람과 장소의 속성에 대한 및 중 하나를하는 것은 그들에게 행동의 주 속성을 만들거나 적어도 액션의 메소드에 인수로 전달할 예

class Place 
{ 
    private $name; 

    public function __construct($name) 
    { 
     $this->name = $name; 
    } 

    public function getName() 
    { 
     return $this->name; 
    } 
} 

class Person 
{ 
    private $name; 
    private $age; 

    public function __construct($name, $age) 
    { 
     $this->name = $name; 
     $this->age = $age; 
    } 

    public function getName() 
    { 
     return $this->name; 
    } 

    public function getAge() 
    { 
     return $this->age(); 
    } 
} 

class Action 
{ 
    private $person; 
    private $place; 

    public function __constuct(Person $person, Place $place) 
    { 
     $this->person = $person; 
     $this->place = $place; 
    } 

    public function drive() 
    { 
     if ($this->person->getAge() < 18) { 
      throw new Exception('Too young to drive!'); 
     } 

     if ($this->place->getName() != 'parking') { 
      throw new Exception("Not parking, can't drive!"); 
     } 

     // start driving 
    } 
}