правильно установить взаимозависимость между классами

Beavis

Banned
нужно установить связь 1к1 между объектами двух классов
как это сделать правильно?

PHP:
<?php

class Mother {
	protected $child;

	public function setChild(Child $child) {
		$this->child = $child;
		$child->setMother($this);
	}
}

class Child {
	protected $mother;
	
	public function setMother(Mother $mother) {
		$this->mother = $mother;
		$mother->setChild($this);
	}
}

$mother = new Mother();
$child = new Child();

$mother->setChild($child);
 

ldaniil

Новичок
PHP:
class Mother {
    protected $child;

    public function setChild(Child $child) {
        if (empty($this->child))
        {
            $this->child = $child;
            $child->setMother($this);
        }
    }
}

class Child {
    protected $mother;
    
    public function setMother(Mother $mother) {
        if (empty($this->mother))
        {
            $this->mother = $mother;
            $mother->setChild($this);
        }
    }
}
 

Beavis

Banned
тогда вторая строчка кода не выполнится
PHP:
$mother->setChild($child);
$mother->setChild($child_another);
 

ldaniil

Новичок
значит в проверку нужно ещё добавить сравнение объектов
 

rotoZOOM

ACM maniac
Или:
PHP:
<?php

class Mother {
    protected $child;

    public function setChild(Child $child) {
        $this->child = $child;
    }
}

class Child {
    protected $mother;
    
    public function setMother(Mother $mother) {
        $this->mother = $mother;
    }
}

$mother = new Mother();
$child = new Child();

// контроллер, который знает/создает мать и дитя, сам занимается их привязкой
$mother->setChild($child);
$child->setMother($mother);
Или:
PHP:
<?php

class Mother {
    protected $child;

    public function setChild(Child $child) {
        $this->child = $child;
        $child->setMother($this);
    }
}

class Child {
    protected $mother;
    
    public function setMother(Mother $mother) {
        $this->mother = $mother;
    }
}

$mother = new Mother();
$child = new Child();

// добавляем только ребенка к матери
$mother->setChild($child);
 

Absinthe

жожо
В изначальный код добавить второй параметр $linked=true, а из методов классов вызывать с false.
 

grigori

( ͡° ͜ʖ ͡°)
Команда форума
нужно установить связь 1к1 между объектами двух классов
как это сделать правильно?
Через фабрику.
PHP:
class A {
public $child = null;
protected function giveBirth($childClassName){
 if ($this->child){
    throw new Exception;
 }
 $child = new $childClassName();
 $this->child = $child;
 }
}
}

class B extends A{
private $parent;
protected __construct(){
}
public static function factory(A $parent){
    return $this->parent = $parent->giveBirth(__CLASS__);
}

}

try{
$A = new A();
$B = B::factory($A);
}catch{}
как-то так.
 
Сверху