tags:

views:

36

answers:

2

here is my setup.

class testA {

    function doSomething() {
    return something;
    }

}

$classA = new testA();

class testB {

 $classA->doSomething();


}

this wont work inside that class.: $classA->doSomething(); how else would i do it?

A: 

You cannot put statements inside classes like that. The statement $classA->doSomething() has to be inside a function as well.

Thomas
can you explain please?
michael
I could, but I suggest you pick up a good book about PHP and object-oriented programming instead.
Thomas
+2  A: 

There are 2 ways to do it: aggregation and composition

Aggregation is when you pass a reference to an object. If the container objected is destroyed the contained object isnt

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

Composition is when an object is owned by another object. So if the owner is destroyed, both are destroyed.

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
Galen