Interfaces in oops and when to use interface
What are the interfaces in oops, Introduction:
When we start oops concept some of the features come in mind. Interfaces are one of the OOPS concepts and as we all know OOPS provides the inheritance to reuse the existing code and functionality. But in general, OOPS doesn’t allow multiple inheritances and to overcome this drawback in PHP interfaces help to achieve multiple inheritances with other features also. Keep reading on this might help you to crack the interview.
What are the interfaces in PHP?
The interfaces are similar to the abstract classes but the only difference is that interfaces can not have concrete methods. And interfaces can have only the abstract method. One more difference is that interfaces allow multiple inheritance and abstract classes don’t allow multiple inheritances. In other words, interfaces are constructed in OOPS and those construct can be used by the classes which inherit the interfaces. Interfaces are very helpful in kind of metadata for all the methods that the programmer has to implement.
How to create interfaces?
Interfaces can be created in the same way that we create a class but it starts with the keyword interface.
<?php interface interfaceName { public function methodNameOne(); public function methodNameTwo(); }
When to use interfaces?
When you wish to make a template that acts as a structure for other programmers.
When a class that should be served as a parent class.
When you are not sure what is the complete details that come in the method.
How a class can implement the interface?
Any class can implement the interfaces by using the keyword interface. Let take an example. The interface defined as the player has the abstract methods called play and pause that every audio player should have and audio player class must implement all the methods declared in the interface call player otherwise it will through an error.
<?php interface player { public function pay(); public function pause(); } class audioPlayer implements player { public function pay() { echo "Audio is playing\n"; } public function pause() { echo "Audio is paused"; } } $playerObject = new audioPlayer(); $playerObject->pay(); $playerObject->pause(); //Output Audio is playing Audio is paused
Behavior or rules of interfaces.
Interfaces can have only abstract methods and not implementation.
Interfaces can contain concrete methods.
Interfaces methods must be public visibility scope
Interfaces support multiple inheritances
Also, read What is inheritance?
One thought on “Interfaces in oops and when to use interface”
Comments are closed.