Explain Encapsulation in PHP.

PHPObject Oriented ProgrammingProgramming

Object Oriented Programming is a software approach added to PHP5, which helps in building the composite application in an easy way. Some of the OOP concepts added into the PHP5 are an abstraction, interface, static method, and static class, etc...

In this article, we will learn Encapsulation and it's implementation through a few examples.

The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Encapsulation is a protection mechanism for the data members and methods present inside the class. In the encapsulation technique, we are restricting the data members from access to outside world end-user.

In PHP, encapsulation utilized to make the code more secure and robust. Using encapsulation, we are hiding the real implementation of data from the user and also does not allow anyone to manipulate data members except by calling the desired operation.


Let' understand this through an example.

   class ATM {
      private $custid;
      private $atmpin;
      public function PinChange($custid,$atmpin) {
               ---------perform tasks-----
      public function CheckBalance($custid,$atmpin){
               ---------perform tasks-----
      public function miniStatement($custid) {
               ---------perform tasks-----
   $obj = new ATM();
   $obj ->CheckBalance(10005285637,1**3);


In this example, all the ATM class data members (variable) are marked with the private modifier. It implies that we can not directly access ATM class data members (property). So, we can't change the class property directly. The only approach to change the class property (data members) is calling a method (function). That’s the reason we have stated all the ATM class methods with a public access modifier. The user can pass the expected arguments to a class method to perform a particular task. 

Suppose anyone wants to check balance then he needs to access the CheckBalance() method with the required arguments $custid="10005285637" and $atmpin="1**3". This is called Data hiding through Encapsulation.


We can achieve Encapsulation in PHP through by implementing Access specifiers.

Published on 11-Jun-2019 10:58:24