PHP Interfaces
PHP - What are Interfaces?
A interface is used to make collection of methods into a groups and to support multiple inheritence.
You can specify which methods a class should implement by using interfaces definitions.
Interfaces make it simple to use multiple classes at the same time. "Polymorphism" is a term that refers to when two or more classes share the same interfaces.
The interface
keyword is used to declare interfaces in a program :
Syntax :-
PHP - Interfaces vs. Abstract Classes
Abstract classes and interfaces are comparable. The distinction between interfaces and abstract classes is as follows :
- In contrast, abstract classes can have characteristics.
- Abstract class methods are either
public
orprotected
, while interface methods are required to be public accessible. - It is not essential to use the keyword
abstract
because all methods in an interface are abstract. - Inheritance from one class and implementation of an interface are both possible.
Related Links
PHP - Using Interfaces
A class must employ the implements
keyword in order to implement an interface.
All of the methods of an interface must be implemented by a class that implements it.
Example 1 :-
makeSound();
?>
Output :-
Assume we want to create software that handles a group of animals based on the preceding example. There are some actions that all of the animals can perform, but each species executes it in its own unique way.
Example 2 :- We can develop code that works for all of the animals, even if they behave differently, by using interfaces :
makeSound();
}
?>
Output :-
Example Explained :-
The Animal interface is implemented by Cat, Dog, and Mouse, therefore they can all generate sounds with the makeSound()
method. As a result, even if we don't know what kind of animal each one is, we can loop through all of them and order them to create a sound.
A method's implementation is not specified in the interface, which means that each animal's sound is unique.
Related Links