Интерфейсы объектов

Интерфейсы объектов позволяют программисту создавать код, который указывает, какие методы и свойства должен включать класс, без необходимости описывания их функционала.

Интерфейсы объявляются так же, как и обычные классы, но с использованием ключевого слова "interface"; тела методов интерфейсов должны быть пустыми. Для включения интерфейса в класс программист должен использовать ключевое слово "implements" и описать функционал методов, перечисленных во включаемом интерфейсе. Если это требуется, классы могут включать более одного интерфейса путём их перечисления через пробел.

Если класс включает какой-либо интерфейс и не описывает функционал всех методов этого интерфейса, выполнение кода с использованием такого класса завершится фатальной ошибкой, сообщающей, какие именно методы не были описаны.

Пример #1 Пример интерфейса

<?php
interface ITemplate
{
  public function 
setVariable($name$var);
  public function 
getHtml($template);
}

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;
  }
}
?>

Коментарии

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 
'Interface constant';
}

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

class 
implements a
{
}

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

echo 
c::b;
?>
2011-03-03 15:37:46
http://php5.kiev.ua/manual/ru/language.oop5.interfaces.html
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.
2014-08-10 13:42:28
http://php5.kiev.ua/manual/ru/language.oop5.interfaces.html
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
2021-03-09 11:44:56
http://php5.kiev.ua/manual/ru/language.oop5.interfaces.html
Автор:
Just as all interface methods are public, all interface methods are abstract as well.
2021-12-30 23:07:27
http://php5.kiev.ua/manual/ru/language.oop5.interfaces.html

    Поддержать сайт на родительском проекте КГБ