Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is encapsulation with simple example in php?

People also ask

What is encapsulation with example?

Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines. We can create a fully encapsulated class in Java by making all the data members of the class private.

What is encapsulation in simple words?

By definition, encapsulation describes the idea of bundling data and methods that work on that data within one unit, like a class in Java. This concept is also often used to hide the internal representation, or state of an object from the outside. This is called information hiding.

How do you achieve data encapsulation in PHP give examples?

Encapsulation in PHP can be achieved using the implementation of access specifiers. It is very careful about OOPs concept of inheritance as many times inheritance can undermine the concept of encapsulation. Inheritance exposes some details of a parent class, effectively breaking encapsulation.

What is the best example of encapsulation?

School bag is one of the most real examples of Encapsulation. School bag can keep our books, pens, etc. Realtime Example 2: When you log into your email accounts such as Gmail, Yahoo Mail, or Rediff mail, there is a lot of internal processes taking place in the backend and you have no control over it.


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

Here's an example from the first link in a Google search for 'php encapsulation':

<?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();

?>

Encapsulation is protection mechanism for your class and data structure. It makes your life much easier. With Encapsulation you have a control to access and set class parameters and methods. You have a control to say which part is visible to outsiders and how one can set your objects parameters.

Access and sett class parameters

(Good Way)

<?php

class User
{
    private $gender;

    public function getGender()
    {
        return $this->gender;
    }

    public function setGender($gender)
    {
        if ('male' !== $gender and 'female' !== $gender) {
            throw new \Exception('Set male or female for gender');
        }

        $this->gender = $gender;
    }
}

Now you can create an object from your User class and you can safely set gender parameters. If you set anything that is wrong for your class then it will throw and exception. You may think it is unnecessary but when your code grows you would love to see a meaningful exception message rather than awkward logical issue in the system with no exception.

$user = new User();
$user->setGender('male');

// An exception will throw and you can not set 'Y' to user gender
$user->setGender('Y');

(Bad Way)

If you do not follow Encapsulation roles then your code would be something like this. Very hard to maintain. Notice that we can set anything to the user gender property.

<?php

class User
{
    public $gender;
}

$user = new User();
$user->gender = 'male';

// No exception will throw and you can set 'Y' to user gender however 
// eventually you will face some logical issue in your system that is 
// very hard to detect
$user->gender = 'Y';

Access class methods

(Good Way)

<?php

class User
{
    public function doSomethingComplex()
    {
        $this->doThis(...);
        ...
        $this->doThat(...);
        ...
        $this->doThisExtra(...);
    }

    private function doThis(...some Parameters...)
    {
      ...
    }

    private function doThat(...some Parameters...)
    {
      ...
    }

    private function doThisExtra(...some Parameters...)
    {
      ...
    }
}

We all know that we should not make a function with 200 line of code instead we should break it to some individual function that breaks the code and improve the readability of code. Now with encapsulation you can get these functions to be private it means it is not accessible by outsiders and later when you want to modify a function you would be sooo happy when you see the private keyword.

(Bad Way)

class User
{
    public function doSomethingComplex()
    {
        // do everything here
        ...
        ...
        ...
        ...
    }
}

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. The wrapping up of data and methods into a single unit (called class) is known as encapsulation. The benefit of encapsulating is that it performs the task inside without making you worry.


Encapsulation is a way of storing an object or data as a property within another object, so that the outer object has full control over what how the internal data or object can be accessed.

For example

class OuterClass
{
  private var $innerobject;

  function increment()
  {
    return $this->innerobject->increment();
  }
}

You have an extra layer around the object that is encapsulated, which allows the outer object to control how the inner object may be accessed. This, in combination with making the inner object/property private, enables information hiding.