Using Interface in PHP

In this blog post, I’ll discuss what is an interface in PHP. How interfaces help us to manage codebase. What’s the importance of an interface in our code ?

What is Interface in PHP ?

Interfaces allow you to define a common structure for class. You can think an interface as a contract. Through interfaces, we lay out some rules, the classes that implement interfaces must follow those rules.

NOTE : Interfaces will not add any additional functionality in your code but it outlines a standard format to which your classes need to use.

Learn PHP programming online : Video tutorials 

How to Create and Implement an Interface in PHP

An Interface can be created through interface keyword followed by interface name. In interfaces, methods are not defined, the class which implements must define all the methods of an interface. All the methods declare in an interface should be public. Unlike an  abstract class, PHP class can implement multiple interfaces.

PHP Traits

Subscribe Our Tutorials

Get Latest Updates on Facebook

Let’s create a cache interface which has two methods such as setKey and getKey. Any class which implements Cache interface, define a setKey and getKey method.

To use interface in a class, implements keyword is used.

Some predefined interfaces in PHP.

PHP 7 Features

Why We Use Interfaces in our Code ?

i) An interface allow  us to hide an implementation details.

ii) To implement multiple behaviours into a single class (build complex types)

Conclusion

The use of Interfaces , Abstract Classes,  Traits in a program is not mandatory but it allows you to manage code and keep it well structured.

PHP Object-Oriented Programming Books

PHP OOPs Concept

PHP Books on Amazon India

WebRewrite

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.