{ private $radius; public function __construct($x, $y, $radius) { parent::__construct($x, $y); $this->radius = $radius; } protected function drawShape() { return "Рисуем окружность с радиусом {$this->radius}"; } } class Rectangle extends Shape { private $width; private $height; public function __construct($x, $y, $width, $height) { parent::__construct($x, $y); $this->width = $width; $this->height = $height; } protected function drawShape() { return "Рисуем прямоугольник с шириной {$this->width} и высотой {$this->height}"; } } $circle = new Circle(0, 0, 50); $rectangle = new Rectangle(0, 0, 100, 50); $circle->draw(); $rectangle->draw();
<?php /*АБСТРАКТНЫЕ КЛАССЫ И МЕТОДЫ*/ //Абстрактный метод - это метод реализация которого отсутствует. После написания функция сразу ставим точку с запятой (abstract function draw();) //Абстрактный класс- это класс, который содержит хотя бы один абстрактный метод. Имеет два свойства: 1 - создать объект абстрактного класса невозможно; 2 - невозможно воспользоваться абстрактными методами, если они не переопределены в производных классах(классах наследниках) //Ключевое слово abstract - объявляет класс абстрактным require_once getenv("DOCUMENT_ROOT") . "/lib/config.php"; require_once "Circle.php"; $shape = new Circle(50, 20, 10); $shape->moveTo(30, 40); $shape->draw();
{ protected $decoratedShape; function __construct(Shape $decoratedShape) { $this->decoratedShape = $decoratedShape; } function draw() { $this->decoratedShape->draw(); } } class RedShapeDecorator extends ShapeDecorator { function __construct(Shape $decoratedShape) { parent::__construct($decoratedShape); } private function setRedBorder() { echo 'Border color: red'; } function draw() { $this->decoratedShape->draw(); $this->setRedBorder(); } } $c = new Circle(); $c->draw(); $rc = new RedShapeDecorator($c); $rc->draw();
protected function __construct($drawAPI) { $this->drawAPI = $drawAPI; } public abstract function draw(); } // create concrete class implementing the Shape interface (abstract class) class Circle extends Shape { private $x; private $y; private $radius; public function __construct($x, $y, $radius, $drawAPI) { Shape::__construct($drawAPI); $this->x = $x; $this->y = $y; $this->radius = $radius; } public function draw() { $this->drawAPI->drawCircle($this->radius, $this->x, $this->y); } } // Use Shape and DrawAPI classes to draw different colored circles // implementation of concrete circles selected at run time. $redCircle = new Circle(100, 100, 10, new RedCircle()); $greenCircle = new Circle(100, 100, 10, new GreenCircle()); $redCircle->draw(); $greenCircle->draw();