对象作为属性,得到父类

问题描述:

我有2个类,BeerIngredient对象作为属性,得到父类

我的课Beer得到了一个名为$ingredients的属性,它是一个Ingredient对象的数组。

如果有办法,在我的Ingredient类我能确定,如果这个目的是通过实例化,或者属于Beer$ingredients财产?

+1

你是什么意思的“instanced by _hand_”? – SOFe

+0

我的意思是在我的代码中有这样的:$ ingredient = new Ingredient(2); – Treast

+0

等一下,除了使用构造函数之外,还有其他方法可以创建'Ingredient'吗? – SOFe

没有隐式的方法。发生这种情况时,您必须通知实例。

见这个例子:

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()使用。