Organizing Classes
Posted: Sun Feb 15, 2009 10:59 pm
Well, you're all going to be happy with me. I have decided to fully transition to OO. I have held out as long as I can. I am currently reviewing best practices and putting a lot of thought into how classes should be structured and organized. I have a lot of questions, but for now I'm going to start with this.
I've created a very simple, perhaps too simple example below. It's a calculator that can add and subtract. Adding new classes to divide or multiple is very simple. But what if I want to add the ability for the calculator to accept an arbitrary number of values so that an average can be calculated? Did I build this wrong from the start?
I've created a very simple, perhaps too simple example below. It's a calculator that can add and subtract. Adding new classes to divide or multiple is very simple. But what if I want to add the ability for the calculator to accept an arbitrary number of values so that an average can be calculated? Did I build this wrong from the start?
Code: Select all
abstract class Calc {
abstract function calculate();
public function setValues($x, $y) {
$this->x = $x;
$this->y = $y;
}
public function getAnswer() {
return $this->calculate();
}
}
class Calc_Add extends Calc {
public function calculate() {
return $this->x + $this->y;
}
}
class Calc_Subtract extends Calc {
public function calculate() {
return $this->x - $this->y;
}
}
$calc = new Calc_Add();
$calc->setValues(10, 10);
echo $calc->getAnswer();