【问题标题】:Object as attribute, get parent class对象作为属性,获取父类
【发布时间】:2017-01-25 17:36:57
【问题描述】:

我有 2 个课程,BeerIngredient

我的班级Beer 有一个名为$ingredients 的属性,它是Ingredient 对象的数组。

如果有办法在我的Ingredient 类中确定该对象是由hand 实例化,还是属于Beer$ingredients 属性?

【问题讨论】:

  • “由手工实例化”是什么意思?
  • 我的意思是在我的代码中有这样的:$ingredient = new Ingredient(2);
  • 等等,除了使用构造函数,还有其他方法可以创建Ingredient吗?

标签: php oop


【解决方案1】:

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

看这个例子:

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->hasOwner() 检查Ingredient 的实例是否在Beer 中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2016-07-15
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多