March 28, 2012
Why doesn't this work? OOP novice
Question by Sorrybyenglish
I am new to OOP, so please do not be harsh.
My task is that this:
$color = new Color(127,0,0);
$rect = new Rectangle($color, 100, 50);
$rect->render();
Should bring to the page the following code:
"div style="background-color:RGB(127,0,0);width:100px;height:50px"></div>"
Below is my OOP code. The goal was to use an abstract class Component
and with an abstract method render()
. I am trying to figure out why code doesn’t work:
class Color {
protected $red;
protected $green;
protected $blue;
public function __construct($red, $green, $blue) {
$this->red = $red;
$this->green = $green;
$this->blue = $blue;
}
}
abstract class Component {
protected $color;
protected $width;
protected $height;
public function __construct($color) {
$this->color = new Color();
}
abstract function render();
}
class Rectangle extends Component {
public function __construct($color, $width, $height){
parent::__construct();
$this->color = $color;
$this->width = $width;
$this->height = $height;
}
public function render() {
echo "<div style='background-color:RGB(" . $this->color . ");width:" . $this->width . "px;height:" . $this->height . "px'></div>";
}
}
$color = new Color(127,0,0);
$rect = new Rectangle($color, 100, 50);
echo $rect->render();
Answer by Starx
You haven’t passed the $color
object to the parent class, and the spelling of width
is incorrect
public function __construct($color, $width, $height){
parent::__construct($color); //The parent also needs a $color as it is defined
$this->color = $color;
$this->width = $width;
$this->height = $height;
}