Słowo kluczowe interface

Słowo kluczowe interface jest używane do tworzenia interfejsów - specjalnych konstrukcji, które definiują jakie metody powinna zaimplementować klasa. Interfejsy zawierają tylko deklaracje metod bez ich implementacji. Klasa, implementująca interfejs, musi zawierać wszystkie metody zadeklarowane w interfejsie.

Składnia

phpinterface InterfaceName {
  public function method1();
  public function method2($param);
  // ...
}

Przykład

Stwórzmy prosty interfejs i klasę, która go implementuje:

php<?php
  interface Logger {
    public function log($message);
  }

  class FileLogger implements Logger {
    public function log($message) {
      echo "Logging to file: " . $message;
    }
  }

  $logger = new FileLogger();
  $logger->log("Test message");
?>

Wynik wykonania kodu:

php'Logging to file: Test message'

Przykład

Interfejs może zawierać kilka metod, a klasa musi zaimplementować je wszystkie:

php<?php
  interface Shape {
    public function calculateArea();
    public function calculatePerimeter();
  }

  class Circle implements Shape {
    private $radius;
    
    public function __construct($radius) {
      $this->radius = $radius;
    }
    
    public function calculateArea() {
      return 3.14 * $this->radius * $this->radius;
    }
    
    public function calculatePerimeter() {
      return 2 * 3.14 * $this->radius;
    }
  }

  $circle = new Circle(5);
  echo "Area: " . $circle->calculateArea();
?>

Wynik wykonania kodu:

php'Area: 78.5'

Zobacz też

  • polecenie class,
    do deklarowania klas
  • polecenie trait,
    do deklarowania traitów