Treast Treast - 2 months ago 7
PHP Question

Object as attribute, get parent class

I've got 2 classes,

Beer
and
Ingredient
.

My class
Beer
got a property called
$ingredients
that is a array of
Ingredient
objects.

If there a way that in my
Ingredient
class I can determine if this object is instanced by hand, or belongs to the
$ingredients
property of a
Beer
?

Answer

No implicit methods. You must notify the instance when that happens.

See this example:

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

Now you can check if an instance of Ingredient is used in a Beer using $ingredient->hasOwner().

Comments