php oop interfaces

PHP OOP Interfaces

PHP interface is 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.

Why Using Interface Rather Than Abstract Method

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.

Differece between Abstract Class & 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 constructor. It does not contain a constructor.
Abstract class members can be static. The interface can not contain static members.

How to declare and implement an interface?

The interface can be defined using the interface keyword and the class that inherits from an interface, use the implements keywords.


Implemented Class

Source Code

Try it now

Implementing Multiple Interfaces

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

Try it now

PHP Class - Extends & Implements

A PHP class extends another class and simultaneously implements more than one interface.

Source Code

Try it now