2016-09-17 66 views
-6

我有2個類,BeerIngredient對象作爲屬性,得到父類

我的課Beer得到了一個名爲$ingredients的屬性,它是一個Ingredient對象的數組。

如果有辦法,在我的Ingredient類我能確定,如果這個目的是通過實例化,或者屬於Beer$ingredients財產?

+1

你是什麼意思的「instanced by _hand_」? – SOFe

+0

我的意思是在我的代碼中有這樣的:$ ingredient = new Ingredient(2); – Treast

+0

等一下,除了使用構造函數之外,還有其他方法可以創建'Ingredient'嗎? – SOFe

回答

0

沒有隱式的方法。發生這種情況時,您必須通知實例。

見這個例子:

class Beer{ 
    private $ingredients = []; 

    public function addIngredient(Ingredient $ing){ 
     $this->ingredients[] = $ing; 
     $ing->setOwner($this); 
    } 
} 

class Ingredient{ 
    private $owner; 

    public function getOwner(){ 
     return $this->owner; 
    } 

    public function setOwner($owner){ 
     $this->owner = $owner; 
    } 

    public function hasOwner() : bool{ 
     return isset($this->owner); 
    } 
} 

現在你可以檢查的Ingredient一個實例是在Beer使用$ingredient->hasOwner()使用。