Difference between interface and abstract class in php

Introduction 

Before diving deep into the difference between abstract class and interface, you must understand one basic thing: these are two completely different classes that cannot be used as an alternative to one another.

Interface classes completely empty the shells while expecting child classes to implement everything for them. Abstract classes not only contain the common piece of information between the shells inside but also expect the child classes within to fill in the gaps.

Let us dive in a bit deeper to actually understand the difference minutely.

If you want to read about PHP Array questions then you can visit here. This will help you crack your PHP interviews.

Interface Class

As we already know, an interface is actually defined by an interface keyword where all the methods are abstract. In addition to this, all the methods declared in this type of class must be declared in public which reflects the true nature of an interface.

Let's help to demonstrate that with an example:

  1. interface Logger {  
  2.     public  
  3.     function execute[];  
  4. }  

As you can see above, in the interface, the method body is not defined. Only the name and the parameters are being defined. Now, let's move on to the abstract class.

Abstract Class

In PHP, an abstract class is one being partially implemented by any developer. It might contain at least one abstract method which is basically a method without any written code. It just contains the name and the parameters and has been marked as “abstract”.

By definition, an abstract class is simply a function definition whose purpose is to serve the programmer by telling them the method in question must be implemented in a child class.

Here is an example to demonstrate the abstract class:

  1. abstract class AbstractClass {  
  2.     abstract protected  
  3.     function getValue[];  
  4.     public  
  5.     function printOut[] {  
  6.         print $this - > getValue[].  
  7.         "\n";  
  8.     }  
  9. }  

Now that you have been acquainted with what is an abstract an interface class, its time to delve into their differences, step by step.

Here’s a table depicting the difference between abstract and interface class in PHP.

Interface Class

Abstract Class

Interface class supports multiple inheritance feature

Abstract class does not support multiple inheritances.

This does not contain a data member.

Abstract class does contain a data member.

The interface does not allow containers.

The abstract class supports containers.

An interface class only contains incomplete members which refer to the signature of the member.

Abstract class contains both incomplete[i.e. abstract] and complete members.

Since everything is assumed to be public, an interface class does not have access modifiers by default.

An abstract class can contain access modifiers within subs, functions, and properties.

Any member of an interface cannot be static.

Only a complete member of the abstract class can be static.

Conclusion 

Now that you have learned abstract class and interface differences, it will be much easier to implement them on your project. 

Many junior developers make the mistake of thinking of interfaces, abstract and concrete classes as slight variations of the same thing, and choose one of them purely on technical grounds: Do I need multiple inheritance? Do I need some place to put common methods? Do I need to bother with something other than just a concrete class? This is wrong, and hidden in these questions is the main problem: "I". When you write code for yourself, by yourself, you rarely think of other present or future developers working on or with your code.

Interfaces and abstract classes, although apparently similar from a technical point of view, have completely different meanings and purposes.

Summary

  1. An interface defines a contract that some implementation will fulfill for you.

  2. An abstract class provides a default behavior that your implementation can reuse.

Alternative summary

  1. An interface is for defining public APIs
  2. An abstract class is for internal use, and for defining SPIs

On the importance of hiding implementation details

A concrete class does the actual work, in a very specific way. For example, an ArrayList uses a contiguous area of memory to store a list of objects in a compact manner which offers fast random access, iteration, and in-place changes, but is terrible at insertions, deletions, and occasionally even additions; meanwhile, a LinkedList uses double-linked nodes to store a list of objects, which instead offers fast iteration, in-place changes, and insertion/deletion/addition, but is terrible at random access. These two types of lists are optimized for different use cases, and it matters a lot how you're going to use them. When you're trying to squeeze performance out of a list that you're heavily interacting with, and when picking the type of list is up to you, you should carefully pick which one you're instantiating.

On the other hand, high level users of a list don't really care how it is actually implemented, and they should be insulated from these details. Let's imagine that Java didn't expose the List interface, but only had a concrete List class that's actually what LinkedList is right now. All Java developers would have tailored their code to fit the implementation details: avoid random access, add a cache to speed up access, or just reimplement ArrayList on their own, although it would be incompatible with all the other code that actually works with List only. That would be terrible... But now imagine that the Java masters actually realize that a linked list is terrible for most actual use cases, and decided to switch over to an array list for their only List class available. This would affect the performance of every Java program in the world, and people wouldn't be happy about it. And the main culprit is that implementation details were available, and the developers assumed that those details are a permanent contract that they can rely on. This is why it's important to hide implementation details, and only define an abstract contract. This is the purpose of an interface: define what kind of input a method accepts, and what kind of output is expected, without exposing all the guts that would tempt programmers to tweak their code to fit the internal details that might change with any future update.

An abstract class is in the middle between interfaces and concrete classes. It is supposed to help implementations share common or boring code. For example, AbstractCollection provides basic implementations for isEmpty based on size is 0, contains as iterate and compare, addAll as repeated add, and so on. This lets implementations focus on the crucial parts that differentiate between them: how to actually store and retrieve data.

APIs versus SPIs

Interfaces are low-cohesion gateways between different parts of code. They allow libraries to exist and evolve without breaking every library user when something changes internally. It's called Application Programming Interface, not Application Programming Classes. On a smaller scale, they also allow multiple developers to collaborate successfully on large scale projects, by separating different modules through well documented interfaces.

Abstract classes are high-cohesion helpers to be used when implementing an interface, assuming some level of implementation details. Alternatively, abstract classes are used for defining SPIs, Service Provider Interfaces.

The difference between an API and an SPI is subtle, but important: for an API, the focus is on who uses it, and for an SPI the focus is on who implements it.

Adding methods to an API is easy, all existing users of the API will still compile. Adding methods to an SPI is hard, since every service provider [concrete implementation] will have to implement the new methods. If interfaces are used to define an SPI, a provider will have to release a new version whenever the SPI contract changes. If abstract classes are used instead, new methods could either be defined in terms of existing abstract methods, or as empty throw not implemented exception stubs, which will at least allow an older version of a service implementation to still compile and run.

A note on Java 8 and default methods

Although Java 8 introduced default methods for interfaces, which makes the line between interfaces and abstract classes even blurrier, this wasn't so that implementations can reuse code, but to make it easier to change interfaces that serve both as an API and as an SPI [or are wrongly used for defining SPIs instead of abstract classes].

Which one to use?

  1. Is the thing supposed to be publicly used by other parts of the code, or by other external code? Add an interface to it to hide the implementation details from the public abstract contract, which is the general behavior of the thing.
  2. Is the thing something that's supposed to have multiple implementations with a lot of code in common? Make both an interface and an abstract, incomplete implementation.
  3. Is there ever going to be only one implementation, and nobody else will use it? Just make it a concrete class.
    1. "ever" is long time, you could play it safe and still add an interface on top of it.

A corollary: the other way around is often wrongly done: when using a thing, always try to use the most generic class/interface that you actually need. In other words, don't declare your variables as ArrayList theList = new ArrayList[], unless you actually have a very strong dependency on it being an array list, and no other type of list would cut it for you. Use List theList = new ArrayList instead, or even Collection theCollection = new ArrayList if the fact that it's a list, and not any other type of collection doesn't actually matter.

What is the difference abstract class and interface?

The Abstract class and Interface both are used to have abstraction. An abstract class contains an abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class. Explore more differences between abstract class and interface in java.

What is class abstract class and interface in PHP?

In PHP, an abstract class is one being partially implemented by any developer. ... Abstract Class..

What is difference between abstract class and interface with real time example?

We can run an abstract class if it has main[] method but we can't run an interface because they can't have main method implementation. Interfaces are used to define contract for the subclasses whereas abstract class also define contract but it can provide other methods implementations for subclasses to use.

What is the difference between trait and interface in PHP?

The main difference between the Traits and Interfaces in PHP is that the Traits define the actual implementation of each method within each class, so many classes implement the same interface but having different behavior, while traits are just chunks of code injected in a class in PHP.

Chủ Đề