Most of the design patterns use interfaces, but interfaces are no design pattern. So from the programming point of view it will not add any additional functionality to your code but it will help up to make some standards for the code you have written.
Interface is some what like as abstract class, you can find more about the abstract class from this article on Abstract in PHP.
Interface is just like a coding standard because interface allow us to create a code/class which specifies the list of methods a class must implement.
We can declare methods and constants in interface. Make sure that declared method must have only declaration part and not the implementation part. Also all methods declared in interface must be public.
Note: All methods declared in interface must be public!!
We can create an interface using the keyword interface. Check out below code that will demonstrate the code to create an basic interface.
You can see that above interface have 2 methods declared. So any class which implement this interface must declare those two methods.
Interface can be implemented using implements operator. All methods declared in the interface must be implemented in class which implement that interface.
It will generate Fatal Error if you do not implement the method which declared in an interface. Please check below code which shows the implementation of the interface.
We can implement more than one interface to one class. In this case interface names should be separated by comma ,.
Same as classes we can extend the interface too using the extends keyword. So once any class implements the interface must implemets all methods from the both parent and child interfaces. Have a look at below code block for the same:
Note: We can not implements two interfaces if same method declared in both interfaces.
Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.
View all posts by: Avinash