PHP Interfaces

PHP Interfaces


An interface is defined the same way as a class, except for the interface keyword. Interface methods are defined the same way as abstract methods except for the abstract keyword.Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism".

Interface declares only the members. The implementation is left to the implementer of the Interface:

Syntax:       

<?php
interface person{
	public function show();
}
?>       

Let's understand Interface a simple example :

Output : hello

Interface Vs Abstract Class In PHP

Interface Abstract Class
An interface cannot use abstract modifier. An Abstract Class must use abstract modifier.
An interface cannot use public, protected, and private access modifiers. An Abstract Class cannot use public, protected, and private access modifiers.
An interface can be declared using interface modifier. Abstract Class can be declared using abstract and class modifiers.
Interfaces cannot use final modifier. Abstract Class cannot use final modifier.
Interfaces can declare constants using the const modifier. Abstract Classes can declare constants using the const modifier.
Interfaces cannot declare public, protected, private, static and final variables. Abstract Classes can declare public, protected, private, static and final variables.
All the functions declared in an Interface are inherently public and abstract. Functions in an Abstract Class must be exclusively declared as public and abstract where required.
The function definition is not allowed in an Interface. We can alternatively use Traits to declare and define functions and to reuse the functions. Functions can be defined in an Abstract Class. Abstract Classes can use Traits.
Interfaces cannot declare private, protected, and final methods. Abstract Class can declare and define private, protected, and final methods.
An Interface can extend either single or multiple Interfaces using the keyword extends. An Abstract Class can extend only a single Abstract Class or Concrete Class using the keyword extends.
An Interface cannot implement another Interface or extend Abstract Class. An Abstract Class can implement either single or multiple Interfaces using the keyword implements.
Interfaces are always 100% abstract. An Abstract Class can be 100% abstract if all the methods declared within the class are abstract.
Interfaces can be used when several classes are required to implement the same methods. Abstract Class can be used to partially implement the features of child classes.
Interfaces can be used for multiple inheritance. Abstract Class can extend another Abstract Class or Concrete Class and implement multiple Interfaces for multiple inheritance.

Implementing multiple interface : In this example we can use multiple interfaces

Output :hello world!