Introduction
In this article you will learn about PHP interfaces. How PHP interfaces are declared and what their use is in PHP. PHP does not support multiple inheritance of classes, to implement multiple inheritance we use an interface in PHP like the other technologies Java, .Net etc.
Most developers know that they cannot use multiple inheritance in PHP. To allow this feature, they use an interface. An interface allows you to define a standard structure for your classes. To define an interface you must use the interface keyword and all methods that are declared in an interface must be public. To implement an interface, the "implements" operator is used. You can implement interfaces that share a function name. You can extend an interface by the use of the "extend" keyword. If we talk about it in simple terms, an interface is like a class using the interface keyword and only contains function declarations (in other words a function without a body).
Some important points about interfaces are:
- You must implement an interface function or say you must declare a body of a method in the derived class otherwise an error message will be generated.
- A class cannot implement two interfaces that share a function name, it would cause ambiguity.
- All methods in an interface must be public.
- All variables in an interface should be constant.
Syntax
access_specifier Interfacee interface_name //access_specifier is public or no_modifier { return_type methodname1(arg list); // Method declaration return_type methodname2(arg list); type variable_name1 = value1; // Variable declaration Note: variables should be constant. type variable_name2 = value2 ----------- ----------- } |
Example of interface in PHP
<?php
interface MyInterface
{
public function add($val1,$val2);
public function sub($val1,$val2);
}
interface MyInterface1 extends Myinterface
{
public function mul($val1,$val2);
public function div($val1,$val2);
}
class Myclass implements MyInterface1
{
public function add($val1,$val2)
{
$sum=$val1+$val2;
echo "Result of Addition is : ". $sum. "</br>";
}
public function sub($val1,$val2)
{
$sub=$val1-$val2;
echo "Result of Substraction is : ". $sub. "</br>";
}
public function mul($val1,$val2)
{
$mul=$val1*$val2;
echo "Result of Multiplication is : ". $mul. "</br>";
}
public function div($val1,$val2)
{
$div=$val1/$val2;
echo "Result of Division is : ". $div. "</br>";
}
}
$obj= new Myclass();
$obj->sub(2,1);
$obj->mul(1,3);
$obj->div(4,2);
$obj->add(4,2);
?>
Output
The differences between a class and an interface are:
Class
- We can extend the class.
- Multiple inheritance is not supported for a class.
Interface
- We can implement an interface.
- An interface can support multiple inheritance.