Learn PHP Tutorial

PHP OOP – Interfaces


Interfaces allow you to specify what methods a class should implement. As a class is a blueprint for objects, similarly an interface is a blueprint for classes.

Interfaces enable you to implement variety of classes in the same manner. When one or more classes uses the same interface, it is referred to as ‘Polymorphism’.

Interfaces in PHP declared with the ‘interface’ keyword followed by the interface name.

Syntax:

<?php
interface my_interface_name
{
	public function methodA();
	public function methodB();
}
?>

Characteristics of an Interface:

  • An interface consists of methods that have no implementations, which means the interface methods are abstract methods.
  • In Interface, all the methods must be defined as public visibility scope.
  • Interfaces are different from classes as the classes can inherit only one class at a time, whereas a class can implement one or more interfaces.

How to use Interface?

To use an interface, a class should use the ‘implements’ keyword.

Syntax:

<?php
class My_class implements my_interface_name
{
		public function methodA()
		{
			//Method A Implementation
		}
		public function methodB()
		{
			//Method A Implementation
		}
}
?>

Let us understand with an example:

<?php
interface Animal
{
	public function make_sound();
}

class Cat implements Animal
{
	public function make_sound()
	{
		echo 'Meow';
	}
}

class Dog implements Animal
{
	public function make_sound()
	{
		echo 'Bark';
	}
}

class Chicken implements Animal
{
	public function make_sound()
	{
		echo 'cluck';
	}
}

//Creating animals list
$cat	 = new Cat();
$dog	 = new Dog();
$chicken = new Chicken();

$animals = array($cat, $dog, $chicken);

//Animals to make sound
foreach($animals as $animal)
{
	$animal->make_sound();
	echo "<br>";
}

?>

Explanation:

Here, in the above example, an interface ‘Animal’ with a method ‘make_sound’. The method ‘make_sound’ does not contain any content. A class implements this interface uses the available method according to the requirement.

Difference between Interface and Abstract Classes:

InterfacesAbstract Class
Interfaces support multiple inheritance feature.Abstract class does not support multiple inheritance.
Interface classes does not contains data members.Abstract classes contain data members.
In Interface, methods should be defined with public visibility scope.In Abstract classes, properties and methods can be public or protected access modifiers.
Any member of an interface can not be static.Only a complete member of an abstract class can be static.