Php Interface

What is Php Interface?

An Interface is kind of like a class, although you can’t use it directly, classes must implement them.
An interface is a blueprint of a class.
Note:-
(i) In the interface, you will declare the functions.
(ii) The class implementing the interface must use the exact same method signatures as are defined in the interface.
(iii) All methods in the interface must be implemented within a class.
(iv) Classes may implement more than one interface if desired by separating each interface with a comma.
(v) It cannot be instantiated just like an abstract class.

Why use Interface
(i) It is used to achieve fully abstraction.
(ii) we can support the functionality of multiple inheritance.
(iii) It can be used to achieve loose coupling.

How to call Interface

when we call interface into class then we use implements and when we call interface into interface then we use extends.

Class call Interface-page0001

Example of Interface

In this eg. communication is a interface which is implement into french class and Indian class.


<?php
Interface communication {
public function language();
}
class French implements communication {
public function language() {
echo 'French person speak usually french language.';
}
}
class Indian implements communication {
public function language() {
echo 'Indian person speak usually hindi language.';
}
}

$fre_obj=new French;
$fre_obj->language(); 

$ind_obj=new Indian;
$ind_obj->language();
?>
Output:- French person speak usually french language.
French person speak usually hindi language.

Multiple inheritance by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.

Multiple Inheritance-page0001

Example:-


<?php
Interface communication {
	public function language();
}

Interface country {
	public function people();
}

class Indian implements communication,country {

	public function people() {
		echo 'Indian people ';
	}

	public function language() {
		echo 'speak usually Hindi language.';
	}

}

$ind_obj = new Indian;
$ind_obj -> people();
$ind_obj -> language();
?>
Output:- Indian people speak usually Hindi language.

Multiple interface inheritance

A class implements interface but one interface extends another interface.

Example:-


<?php
Interface communication {
	public function language();
}

Interface country extends communication {
	public function people();
}

class French implements country {

	public function people() {
		echo 'French people ';
	}

	public function language() {
		echo 'speak usually french language.';
	}

}

$fre_obj = new French;
$fre_obj -> people();
$fre_obj -> language();
?>
Output:- French people speak usually french language.