PHP interfaces are declared with the interface keyword and it has only an abstract method without implementation. All the methods inside the interface will have public access modifier. It can not declare private or protected.
It can not contain member variables(properties).
The class that inherits from an interface use implements
keywords.
The abstract method contains both abstract methods as well non-abstract methods while the interface uses the only abstract method. This is the secret behind the interface.
Abstract Class | Interface |
---|---|
Abstract Class doesn't support multiple inheritances. | Interfaces support multiple inheritances. |
It contains properties. | It does not contain properties. |
It contains abstract as well as non-abstract methods. | It contains only an abstract method. |
It contains a constructor. | It does not contain a constructor. |
Abstract class members can be static. | The interface can not contain static members. |
The interface can be defined using the interface keyword and the class that inherits from an interface, use the implements keywords.
interface interfaceName {
// abstract methods
}
class Child implements interfaceName {
// defines the interface methods and may have its own code
}
Interface Fruits{
public function getTotalCost();
}
class Mango implements Fruits{
public function getTotalCost(){
echo"I will received all the cost.";
}
}
Source Code
<?php
Interface Fruits{
public function getTotalCost();
}
class Mango implements Fruits{
public function getTotalCost(){
echo"I will received all the cost.";
}
}
$obj = new Mango;
echo $obj-> getTotalCost();
?>
A class can implement multiple interfaces by just placing the name of interfaces separated by a comma after the interface keyword.
Let us understand with the help of an example.
Source Code
<?php
Interface userDefinedInterface1 {
public function userMethod1();
}
Interface userDefinedInterface2 {
public function userMethod2();
}
class SubClass implements userDefinedInterface1,
userDefinedInterface2 {
public function userMethod1() {
echo "This is user1 method.";
echo"<br>";
}
public function userMethod2() {
echo "This is user2 method.";
}
}
$obj = new SubClass();
$obj -> userMethod1();
$obj -> userMethod2();
?>
A PHP class extends another class and simultaneously implements more than one interface.
Source Code
<?php
Interface UserInterface {
public function userDefinedMethod();
}
class SuperClass {
public $user;
public function __construct($name) {
$this -> user = $name;
}
}
class ChildClass extends SuperClass implements UserInterface {
function userDefinedMethod() {
echo $this -> user;
}
}
$obj = new ChildClass('Smith');
$obj -> userDefinedMethod();
?>