Praktyczne zastosowanie interfejsów w OOP w PHP

Spróbujmy zastosować interfejsy w praktyce. Rozwiążmy zadanie z figurami z poprzedniej lekcji, ale już używając interfejsów, a nie klas abstrakcyjnych.

A więc, teraz mamy dany interfejs Figure:

Figure.php<?php
  interface Figure
  {
    public function getSquare();
    public function getPerimeter();
  }
?>

Stwórzmy klasę Quadrate, która będzie implementować metody tego interfejsu:

Quadrate.php<?php
  class Quadrate implements Figure
  {
    private $a;
    
    public function __construct($a)
    {
      $this->a = $a;
    }
    
    public function getSquare()
    {
      return $this->a * $this->a;
    }
    
    public function getPerimeter()
    {
      return 4 * $this->a;
    }
  }
?>

Jak to działa: jeśli zapomnimy zaimplementować jakąś metodę, opisaną w interfejsie, PHP wyświetli nam błąd krytyczny. Zaimplementujmy również klasę Rectangle:

Rectangle.php<?php
  class Rectangle implements Figure
  {
    private $a;
    private $b;
    
    public function __construct($a, $b)
    {
      $this->a = $a;
      $this->b = $b;
    }
    
    public function getSquare()
    {
      return $this->a * $this->b;
    }
    
    public function getPerimeter()
    {
      return 2 * ($this->a + $this->b);
    }
  }
?>
Задание 1

Stwórz klasę Disk, implementującą interfejs Figure.