Когда нам нужны интерфейсы в PHP?

Опубликовано: 4 Февраля, 2022

Интерфейс - это определения общедоступных API-интерфейсов, которые должны реализовывать классы (реализующие интерфейс). Он также известен как контракты, поскольку интерфейс позволяет указать список методов, которые должен реализовать класс. Определение интерфейса аналогично определению класса, просто изменив ключевое слово class на interface.

Example:

<?php
interface man {
  
   // List of public methods
  
}

Интерфейсы могут содержать методы и / или константы, но не атрибуты. Константы интерфейса имеют те же ограничения, что и константы классов. Методы интерфейса неявно абстрактны.

Example:

<?php
  
interface IMyInterface {
    const INTERFACE_CONST_1 = 1;
    const INTERFACE_CONST_2 = "a string";
    
    public function method_1();
    public function method_2();
}
?>

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

// Function to Imlements more than one 
// interface by single class.
   
class MyClass implements IMyInterface {
   
    public function method_1() {
   
        // method_1  implementation 
    }
  
    public function method_2() {
   
        // method_2 implementation
    }
}

Interesting Points :

  • A class cannot implement two interfaces that has the a same method name because it would end up with the method ambiguity.
  • Like classes, it is possible to establish an inheritance relationship between interfaces by using the same keyword “extends”.
    Example:
    interface Foo {
      
    }
    interface Bar {
      
    }
    interface Bass extends Foo, Bar {
      
    }

Below is a complete example that shows how interfaces work.
Example:

<?php
  
// PHP program to Implement interface.
   
// Define a new Interface for all "shapes" 
// to inherit
interface Shape {
    
    // Define the methods required for
    // classes to implement
    public function getColor();
    public function setColor($color);    
      
    // Interfaces can"t define common 
    // functions so we"ll just define a 
    // method for all implementations to
    // define
    public function describe();
}
  
// Define a new "Triangle" class that 
// inherits from the "Shape" interface
   
class Triangle implements Shape {
    
    private $color = null;
      
    // Define the required methods defined 
    // in the abstractclass "Shape"
    public function getColor() {
        return $this->color;
    }   
    
    public function setColor($color) {
        $this->color = $color;
    }   
    
    public function describe() {
        return sprintf("GeeksforGeeks %s %s "
            $this->getColor(), get_class($this));
    }   
}
  
$triangle = new Triangle();
  
// Set the color
$triangle->setColor("green");
  
// Print out the value of the describe common 
// method provided by the abstract class will
// print out out "I am an Orange Triange"
print $triangle->describe();
?>

Выход:

 Зеленый треугольник GeeksforGeeks

Важность использования интерфейсов:

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