为什么这不起作用? OOP新手

时间:2012-03-28 05:09:41

标签: php oop

我是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();

2 个答案:

答案 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();

  }