PHP7 OOPs Interface

PHP Interface is declared with the keyword 'interface'. Like a class, it contain properties and methods declaration. Within the interface, the declared method does not have body. PHP does not support multiple inheritance, but the feature of the multiple inheritance is fulfilled by the Interface. In PHP, a class can implement more than one interface separated by comma.

It is basically used to prototype an application that does not contain actual code, but can contain methods and method signatures.


<?php
interface Company{
    public function salary();
}
?>

In the above code, we have created an interface name Company, this contains a function salary.


implements keyword

A class can implement an interface using the 'implements' keyword.

<?php
interface Company{
    public function salary();
}
class Employee implements Company {
    public function salary(){

    }
}
?>

The Employee class implements the Company interface and contains a salary() method. Any class can initialise salary() method that implements Company interface.





Implements Multiple Interfaces

In PHP, a class can implements more than one interface. As in the below example, class Dimension implements two interfaces Width and Height.

<?php
interface Width{
    public function setWidth();
}
interface Height{
    public function setHeight();
}
class Dimension implements Width, Height {
	protected $width;
	protected $height;
	
    public function setWidth($width){
		$this->width = $width;
    }
	public function setHeight($height){
		$this->height = $height;
	}
}
?>







Read more articles


General Knowledge



Learn Popular Language