을 할 수있는 2 가지 방법이 있습니다 : 당신이 개체에 대한 참조를 통과 할 때 통합 및 구성
집계가가. 객체가 파기 된 컨테이너가 파괴되면 포함 된 객체는 제외됩니다.
class testB {
private $classA;
public function setClassA (testA $classA) {
$this->classA = $classA;
}
public function doStuffWithA() {
$this->classA->doSomething();
}
}
$classA = new testA;
$classB = new testB;
// this is the aggregation
$classB->setClassA($classA);
$classB->doStuffWithA();
unset($classB); // classA still exists
컴포지션은 객체가 다른 객체에 의해 소유 된 경우입니다. 그래서 주인이 파괴되면 둘 다 파괴됩니다.
class testB {
private $classA;
public function __construct() {
$this->classA = new testA;
}
public function doStuffWithA() {
$this->classA->doSomething();
}
}
$classB = new testB; // new testA object is created
$classB->doStuffWithA();
unset($classB); // both are destroyed
왜 다른 클래스 메서드를 호출합니까? –
실제 스크립트에서 나는 testA 클래스가 실제로 db가 필요로하는 메소드를 포함하고있는 db 클래스라는 것을 알고있다. 두 번째 클래스는 장바구니 클래스이고 장바구니 클래스 내에서 $ db-> query ("...")와 같은 첫 번째 클래스를 통해 쿼리를 수행하려고합니다. – michael