我是OOP的新手,所以请不要苛刻。
我的任务是:
$color = new Color(127,0,0);
$rect = new Rectangle($color, 100, 50);
$rect->render();
应该为页面带来以下代码:
"div style="background-color:RGB(127,0,0);width:100px;height:50px"></div>"
以下是我的OOP代码。目标是使用抽象类Component
和抽象方法render()
。我试图弄清楚为什么代码不起作用:
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();
答案 0 :(得分:2)
您尚未将$color
对象传递给父类,width
的拼写错误
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;
}
答案 1 :(得分:1)
如果您想回显$this->color
,则应为Color
类定义__toString方法。
class Color {
protected $red;
protected $green;
protected $blue;
public function __construct($red, $green, $blue) {
$this->red = $red;
$this->green = $green;
$this->blue = $blue;
}
public function __toString() {
return "$this->red, $this->green, $this->blue";
}
}
请注意,您的代码中存在拼写错误,with
应为width
。
此外,下面的Rectangle::__construct
方法中的代码
parent::__construct();
$this->color = $color;
应该是
parent::__construct($color);
Component
类应该是(注意__construct的变化):
abstract class Component {
protected $color;
protected $width;
protected $height;
public function __construct($color) {
$this->color = $color;
}
abstract function render();
}