2011-11-09 102 views
0

比方說,我有3個對象:「地點」,「人物」,「動作」。從對象構圖中獲取數據

根據個人的位置和此人的年齡,此人可以採取不同的行動。

例如:

$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. 

我怎樣才能獲得關於從Action類的對象「人」和「地方」的數據?

類的例子:

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. 
    } 
} 

我想我可以發送 「$這一」 從人到行動,當我創建Action對象(即$這個 - >行動=新的行動($本)) ,但是地方數據呢?

回答

0

將Person設置爲Place或Action的屬性是Person的屬性沒有意義。

我會更傾向於創造公共干將的人員和地點的屬性,要麼讓他們行動的注射性能,或者至少它們作爲參數傳遞到行動的方法,例如

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 
    } 
}