Concept of Abstraction, Abstract Class and Abstract Methods in PHP

easy solution web : OOPS in PHP

What is Abstraction in PHP?

In one way, hiding unnecessary details or implementation about the functionality from the user is called  Abstraction.

For Example:-

We all use the functionality of mobile phones like a phone call, send a message, play video etc. But we don’t the implementation of these features on a hardware level and software level. We just use these functionalities without taking care of others things. So here we have an Abstraction between the User and the implementation of these functions.

Why is it important to implement Abstraction in our programming?

Let’s assume A developer has written a code let’s say, for sending an email. So the developer has written thousands of line of code to send an email. Now, this code is running properly and we are able to send our email. Now do other developers need to know the code and the meaning of each line of code to implement this feature in its module or he/she just need to call the functionality for sending the email. Which is good and time saver. You Decide!!

So how can we achieve the Abstraction in PHP

We can implement Abstraction in PHP by using concepts of Abstract Classes

Using above example of implementing the functionality of email sending. Now a developer has developed the code to implement the functionality. But for sending an email you will need some input from the user who uses that code. So to restrict that user PHP has the abstract method inside the abstract class. So the developer will write sending email process code inside an Abstract Class.

What is Abstract Class?

A class having one or more abstract method as its member function is called an Abstract Class.

Example of Abstract class:

abstract class Shape2d{
public $length;
public $width;
public $sides; 
abstract public function setLenth($len); 
abstract public function setWidth($width); 
abstract public function setSides($sides);
public function calculatePerimeter(){
// code to calculate perimeter of shapes
} 
} //This is how we define an Abstract Class

What is Abstract Methods?

Abstract methods can only have names and arguments but without any body code.

Example of Abstract Methods:

abstract public function setLenth($len); 
abstract public function setWidth($width); 
abstract public function setSides($sides);

Some points are required to remember while using Abstract Class:

  1. We are not able to create an object of Abstract Class.
  2. Abstract Class is used by using “extend” keywords by a concrete class.
  3.         A concrete class has to implement all the abstract methods in its class definition. Otherwise, it will throw an error.
  4.         Abstract Class is defined by “abstract” keywords.
  5.         Abstract Methods is defined by “abstract” keywords.