Interfaces

Interfaces erlauben die Erzeugung von Code, der spezifiziert, welche Methoden eine Klasse implementieren muss, ohne definieren zu müssen, wie diese Methoden implementiert werden.

Interfaces werden auf die selbe Weise wie eine Klasse definiert, aber mit dem interface Schlüsselwort anstatt des class Schlüsselworts, und ohne dass eine der Methoden ihren Inhalt definiert.

Alle in einem Interface deklarierten Methoden müssen public sein; dies liegt in der Natur eines Interfaces.

Es ist zu beachten, dass es möglich ist einen Konstruktor in einem Interface zu deklarieren, was in einigen Fällen nützlich sein kann, z.B. für die Verwendung durch Factories.

implements

Um ein Interface zu implementieren, wird der implements-Operator benutzt. Alle Methoden des Interfaces müssen innerhalb der Klasse implementiert werden; Unterlassung wird zu einem fatalen Fehler führen. Klassen dürfen, falls dies gewünscht wird, mehr als ein Interface implementieren, indem man die Interfaces voneinander mit einem Komma abtrennt.

Hinweis:

Vor PHP 5.3.9 konnte eine Klasse nicht zwei Interfaces, die identische Funktionsnamen deklarieren, implementieren, da dies zu Doppeldeutigkeiten führen würde. Neuere Versionen von PHP erlauben dies, solange die doppelten Methoden die gleiche Signatur haben.

Hinweis:

Ein Interface kann ebenso wie eine Klasse mit Hilfe des Schlüsselwortes extends erweitert werden.

Hinweis:

Die Klasse, die das Interface implementiert, muss eine Methodensignatur verwenden, die gemäß LSP (Liskovsches Substitutionsprinzip) kompatibel ist. Andernfalls führt das zu einem fatalen Fehler.

Konstanten

Ein Interface kann Konstanten definieren. Interface-Konstanten funktionieren genauso wie Klassenkonstanten, außer dass sie von anderen Interfaces oder Klassen, die von diesem Interface erben, nicht verändert werden können.

Beispiele

Beispiel #1 Interface-Beispiel

<?php
// Deklariere das Interface 'iTemplate'
interface iTemplate
{
    public function 
setVariable($name$var);
    public function 
getHtml($template);
}

// Implementiere das Interface
// Dies funktioniert
class Template implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
  
    public function 
getHtml($template)
    {
        foreach(
$this->vars as $name => $value) {
            
$template str_replace('{' $name '}'$value$template);
        }
 
        return 
$template;
    }
}

// Dies wird nicht funktionieren
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
}

?>

Beispiel #2 Interface-Vererbung

<?php
interface a

public function foo();


interface 
extends a
{
  public function 
baz(Baz $baz);
}

// Dies Funktioniert 
class implements b
{
  public function 
foo()
  {
  }

  public function 
baz(Baz $baz)
  {
  }
}

// Dies funktioniert nicht und führt zu einem fatalen Fehler
class implements b
{
  public function 
foo()
  {
  }

  public function 
baz(Foo $foo)
  {
  }
}
?>

Beispiel #3 Interface-Mehrfachvererbung

<?php
interface a
{
  public function 
foo();
}

interface 
b
{
  public function 
bar();
}

interface 
extends ab
{
  public function 
baz();
}

class 
implements c
{
  public function 
foo()
  {
  }

  public function 
bar()
  {
  }

  public function 
baz()
  {
  }
}
?>

Beispiel #4 Interfaces mit Konstanten

<?php
interface a
{
  const 
'Interface constant';
}

// Ausgabe: Interface constant
echo a::b;

// Der folgende Abschnitt wird nicht funktionieren, da
// ein Überschreiben der Konstanten nicht gestattet ist.
class implements a
{
  const 
'Class constant';
}
?>

Ein Interface, in Verbindung mit Type Hinting, bietet eine gute Möglichkeit, um sicherzustellen, dass ein bestimmtes Objekt bestimmte Methoden enthält. Siehe instanceof-Operator und Typdeklarationen.

add a note add a note

User Contributed Notes 4 notes

up
17
thanhn2001 at gmail dot com
13 years ago
PHP prevents interface a contant to be overridden by a class/interface that DIRECTLY inherits it.  However, further inheritance allows it.  That means that interface constants are not final as mentioned in a previous comment.  Is this a bug or a feature?

<?php

interface a
{
    const
b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

class
b implements a
{
}

// This works!!!
class c extends b
{
    const
b = 'Class constant';
}

echo
c::b;
?>
up
2
williebegoode at att dot net
9 years ago
In their book on Design Patterns, Erich Gamma and his associates (AKA: "The Gang of Four") use the term "interface" and "abstract class" interchangeably. In working with PHP and design patterns, the interface, while clearly a "contract" of what to include in an implementation is also a helpful guide for both re-use and making changes. As long as the implemented changes follow the interface (whether it is an interface or abstract class with abstract methods), large complex programs can be safely updated without having to re-code an entire program or module.

In PHP coding with object interfaces (as a keyword) and "interfaces" in the more general context of use that includes both object interfaces and abstract classes, the purpose of "loose binding" (loosely bound objects) for ease of change and re-use is a helpful way to think about both uses of the  term "interface." The focus shifts from "contractual" to "loose binding" for the purpose of cooperative development and re-use.
up
0
Anonymous
2 years ago
Notice that in Example 5, public is written as pubic :)
up
0
xedin dot unknown at gmail dot com
3 years ago
This page says that if extending multiple interfaces with the same methods, the signature must be compatible. But this is not all there is to it: the order of `extends` matters. This is a known issue, and while it is disputable whether or not it is a bug, one should be aware of it, and code interfaces with this in mind.

https://bugs.php.net/bug.php?id=67270
https://bugs.php.net/bug.php?id=76361
https://bugs.php.net/bug.php?id=80785
To Top