2010-05-07 5 views
0

여기 내 설정입니다.클래스 내에서 다른 클래스 메소드를 호출하는 방법은 무엇입니까?

class testA { 

    function doSomething() { 
    return something; 
    } 

} 

$classA = new testA(); 

class testB { 

$classA->doSomething(); 


} 

이 클래스에서는 작동하지 않습니다. $ classA-> doSomething(); 그 밖의 방법은 무엇입니까?

+0

왜 다른 클래스 메서드를 호출합니까? –

+0

실제 스크립트에서 나는 testA 클래스가 실제로 db가 필요로하는 메소드를 포함하고있는 db 클래스라는 것을 알고있다. 두 번째 클래스는 장바구니 클래스이고 장바구니 클래스 내에서 $ db-> query ("...")와 같은 첫 번째 클래스를 통해 쿼리를 수행하려고합니다. – michael

답변

0

그런 클래스 안에 문장을 넣을 수 없습니다. 문 $classA->doSomething()도 함수 내부에 있어야합니다.

+0

설명 할 수 있습니까? – michael

+1

할 수는 있지만 PHP와 객체 지향 프로그래밍에 대한 좋은 책을 선택하는 것이 좋습니다. – Thomas

2

을 할 수있는 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 
관련 문제