哪个更好?传递对象引用,或者传递属性本身


Which is better? Passing object references, or passing properties themselves?

class Parent
{
    public function getSomething()
    {
        return '';
    }
    public function createChild($name)
    {
        return new Child ($name, $this);
    }
}
class Child
{
    public function __constructor ($name, Parent $parent)
    {
        $parent->getSomething();
    }
}

在这个代码中,一个Parent创建了一个Child -,而Child想从它的Parent那里得到一些东西,所以有一种循环引用。编辑:所以父母创造了孩子,但是孩子依赖于父母,他们不能成为一个独立的实体,这就是我的感受。如果我把它写成这样,会更好吗?

class Parent
{
    private function getSomething()
    {
        return '';
    }
    public function createChild($name)
    {
        return new Child ($name, $this->getSomething);
    }
}
class Child
{
    public function __constructor ($name, $something)
    {
    }
}

但是在这种情况下,如果Child需要更多呢?通过构造函数将所有这些东西传递给它?

通过构造函数传递所有这些东西给它?

如果Child只需要实例化时存在的某些数据,并且不调用Parent的任何方法,我会说,是的。

原因:最小化耦合。不要引入不必要的依赖项。


但是,由于您提到了"引用",您可能希望Child稍后访问Parent的属性。那么更简洁的方法是通过Parent的访问器方法来实现,而不是通过带引用的后门暴露这些属性。

我明白了,"references"指的是对象引用。这里做了错误的假设