Ključna reč interface

Ključna reč interface koristi se za kreiranje interfejsa - specijalnih konstrukcija koje definišu koje metode klasa mora implementirati. Interfejsi sadrže samo deklaracije metoda bez njihove implementacije. Klasa koja implementira interfejs mora sadržati sve metode deklarisane u interfejsu.

Sintaksa

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

Primer

Kreirajmo jednostavan interfejs i klasu koja ga implementira:

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");
?>

Rezultat izvršavanja koda:

php'Logging to file: Test message'

Primer

Interfejs može sadržati nekoliko metoda, i klasa mora implementirati sve:

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

Rezultat izvršavanja koda:

php'Area: 78.5'

Pogledajte takođe

  • komandu class,
    za deklarisanje klasa
  • komandu trait,
    za deklarisanje trejtova