In PHP, Interface acts as an agreement with implementing class, it must implement all its methods. Following are the features of PHP interfaces.

  1. All Interfaces methods are public.
  2. A class can implement more than one interface.
  3. Interface cannot have properties.
  4. To implement an interface, implement keyword is used.
  5. An interface, objects cannot be created means it cannot be instantiated.
  6. Interface allows multiple inheritance.

Interface Usage

When so many classes have to implement same method for different purpose, interface should be used. So, by this way code reusability and polymorphism is achieved in PHP with interfaces.

Syntax

interface myInterface{
 public function myFunction();
 public function myFunction1(argument,argument1);
}

Interface is declared using interface keyword and interface name with curly braces {}, inside these curly braces interface function must be declared.

Create an interface PHP

interface Language{
 public function language_name($name);
}

Example

<?php
interface Language{
 public function language_name($name);
}

class Programming implements Language{

 public function language_name($name){
   echo $name;
 }
}

class OfficialLanguage implements Language{

 public function language_name($name){
   echo $name;
 }

}

$obj = new Programming();
$obj->language_name('PHP');

$obj = new OfficialLanguage();
$obj->language_name('English');

?>
  1. interface Language with function language_name is declared with a function signature language_name();
  2. class OfficialLanguage and Programming implemented Language interface.
  3. Due to this, class OfficialLanguage and Programming has to implement or provide declaration to all interface Language functions.

Multiple interface with single class

A class can implement one or more than one interfaces, Below is an example.

<?php
interface Country{
 public function country_name($name);
}

interface Language{
 public function language_name($name);
}

class People implements Country, Language{

 public function language_name($name){
   echo $name;
 }
 public function country_name($name){
   echo $name;
 }

}

$obj = new People();
$obj->country_name('USA');
$obj = new People();
$obj->language_name('English');
?>