Abstract Class vs Interfaces in PHP

Abstract class vs interfaces this is the most asked interview question. Interviewer generally want to know what is abstract class and interfaces. How well you understand the difference between abstract class and interface.

Interfaces

An interface is an agreement. When class A implement interface B then it means it contains same public methods with interface B has.

Example –

I have created one cacheInterface which has two public method get and set. Now Memcache class which implement cacheInterface define the get and set method.

Abstract Class

Abstract class is used to define a basic skeleton or blueprint. A class which extends abstract class must defined some or all of it’s abstract methods.

Subscribe Our Tutorials

Get Latest Updates on Facebook

Abstract class Vs Interfaces

1. An abstract class is a class that defines the blueprint for child classes. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.

An interface is a contract. All the method defined in an interface is fully abstract. The child class which implement interface needs to define all of it’s method.

2. A class can extend only one abstract class whereas a class can implement multiple interfaces.

PHP support single inheritance model, As of PHP 5.4 PHP introduces the concept of traits.

3. In Abstract class you can define variables and concrete method (non abstract method) as well. But in interface all the methods are abstract. You can’t define variables but you can define constants in interface.

4. An abstract class is good if you think you need common base class and you add methods in the future. You can’t do this thing in interfaces, otherwise all the classes that implement that interface will have to modified to implement the new methods.

Conclusion

I hope this post gives you the clear idea of what is interface and abstract class. What’s the main difference between them. If you think i miss any point, you can let me know by comment.

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.

Comments are closed.