Concept of Encapsulation in PHP

easy solution web : OOPS in PHP

PHP Encapsulation

Wrapping up of the data into a single unit is called Encapsulation in Object-Oriented Programming Languages. Many people get confused when someone asked them to explain it with some examples. This Concept will come in your way every time when you go for an interview.

So now let’s understand the concept of Encapsulation in OOPs in detail.

Meaning of

Wrapping up of the data into a single unit

It means defining Class Member Variables and Member function inside the class. So when we create a class and define some member variables and function inside the class it becomes a single unit which will be known by the class name together.

This small statement has a very deep meaning.

Why we need Encapsulation?

When we wrap our data into something then it hides details from the user who uses it.

For example: When we create an Object from a Class we don’t know what has been written inside the constructor. How it initializes the value of the member variable, How member function we use through object manipulates the value of the member variables or how it generates the output.

This is the main reason for which we use encapsulation so that unnecessary details should be hidden from users who use the class. To achieve this we often make Member Variables private, So that it cannot be accessed outside the class and if someone wants to access these variable, it should be through the GETTER and SETTER methods.

Example of Encapsulation:-

class Person{
private $name;
public $gender; 
public $address; 
public $height; 
public $color; 
public $race; 
public function __construct($name){ 
$this->race = "human"; 
$this->name = $name;
public function getName(){
return $this->name;
public function setName($name){
$this->name = $name;

So due to Encapsulation, we are able to achieve Data hiding in OOPs.

So finally the concept of Encapsulation in PHP is hiding internal information of an object to protect from the other object.

This is the simple example of encapsulation with the use of Person Class. But sometimes overuse of inheritance undermines encapsulation in Object Oriented Programmings which we need to take care.

Reference from Wikipedia:

Because inheritance exposes a subclass to details of its parent’s implementation, it’s often said that “inheritance breaks encapsulation”

Gang of Four, Design Patterns
In next articles, we will discuss Inheritance and their types supported by PHP.