Почему это не работает?ООП новичок - PullRequest
0 голосов
/ 28 марта 2012

Я новичок в ООП, поэтому, пожалуйста, не будьте резкими.

Моя задача заключается в следующем:

 $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>"

Ниже мой код ООП. Цель состояла в том, чтобы использовать абстрактный класс 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 ]

2 голосов
/ 28 марта 2012

Вы не передали объект $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 голос
/ 28 марта 2012

Если вы хотите повторить $this->color, вы должны определить __ toString метод для Color класса.

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

  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...