Q . What is Encapsulation in Oops ?

Mike Tyson. asked, Jul 22 ' 2018

Can any body explain it with example?

  • oops
  • Encapsulation

2 Answers

Encapsulation is an OOP (Object Oriented Programming) concept in PHP.

Wrapping some data in single unit is called Encapsulation. Encapsulation is used to safe data or information in an object from other it means encapsulation is mainly used for protection purpose.

In technology era, it is essential to maintain your privacy. So for the security reason, Sometime we make private method.

Private method means it can be accessed within same class. Outside, Class can't access private method of other class.That's why encapsulation is known as data hiding is the main advantage for encapsulation.

Second advantage of encapsulation is you can make the class read only or write only by providing setter or getter method.

Capsule is best example of Encapsulation. Capsule basically encapsulate several combination of medicines. Schoolbag is one of best example of Encapsulation. School bag can keep our books, pen etc.

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

Encapsulation is just wrapping some data in an object. The term "encapsulation" is often used interchangeably with "information hiding". Wikipedia has a pretty through article.

Example:

<?php

class App {
     private static $_user;

     public function User( ) {
          if( $this->_user == null ) {
               $this->_user = new User();
          }
          return $this->_user;
     }

}

class User {
     private $_name;

     public function __construct() {
          $this->_name = "Joseph Crawford Jr.";
     }

     public function GetName() {
          return $this->_name;
     }
}

$app = new App();

echo $app->User()->GetName();

?>

 

Leave a Ansewer