-6
我有2個類,Beer
和Ingredient
。對象作爲屬性,得到父類
我的課Beer
得到了一個名爲$ingredients
的屬性,它是一個Ingredient
對象的數組。
如果有辦法,在我的Ingredient
類我能確定,如果這個目的是通過手實例化,或者屬於Beer
的$ingredients
財產?
我有2個類,Beer
和Ingredient
。對象作爲屬性,得到父類
我的課Beer
得到了一個名爲$ingredients
的屬性,它是一個Ingredient
對象的數組。
如果有辦法,在我的Ingredient
類我能確定,如果這個目的是通過手實例化,或者屬於Beer
的$ingredients
財產?
沒有隱式的方法。發生這種情況時,您必須通知實例。
見這個例子:
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()
使用。
你是什麼意思的「instanced by _hand_」? – SOFe
我的意思是在我的代碼中有這樣的:$ ingredient = new Ingredient(2); – Treast
等一下,除了使用構造函數之外,還有其他方法可以創建'Ingredient'嗎? – SOFe