Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: When to use abstract and interface class?

Tags:

oop

php

I was wondering how you guys decide when to use abstract or interface class during the application development since they both provide similar functionalities with slightly difference. I appreciate any helps. Thanks.

like image 936
FlyingCat Avatar asked Sep 06 '10 18:09

FlyingCat


People also ask

When should we use interface and abstract class in PHP?

In PHP you can use interfaces define common functionality that is provided my similar classes. Abstract classes are used to define base classes that provide common functionality. Despite interfaces and abstract classes are somewhat related, they are not the same.

When would you want to use an abstract class and interface?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

Why do we need both interface and abstract classes?

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated. But there are many differences between abstract class and interface that are given below. 1) Abstract class can have abstract and non-abstract methods.

Where do we use abstract class and interface in real life scenario?

A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it".


2 Answers

Use abstraction if you have default methods (with accompanying code) for inheritors. Use interfaces if you just need to make sure that classes inheriting from this parent should implement all methods defined. Word of caution: use abstract classes and interfaces only if you intend to enforce structure and organization (usually with a team). There's a performance overhead.

like image 81
bcosca Avatar answered Sep 17 '22 17:09

bcosca


I use abstract classes when I want the inheriting classes to inherit some functionality, and interfaces when I want to set some minimum structural criteria for a group of classes.

One thing to remember is that any given class can "inherit" (technically implement) many interfaces but only one sub-class (be that abstract or not).

like image 41
Robin Avatar answered Sep 21 '22 17:09

Robin