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?
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?
You cannot put statements inside classes like that. The statement $classA->doSomething()
has to be inside a function as well.
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