Answer

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

?>
  • 39
Reply Report
      • 1
    • Hi fiXedd, I dont think this is a good and simple example of encapsulation in php. For beginners it is hard to understand the concept of Singleton.
      • 1
    • The naming App->User() is not really a good one is it? It's confusing for people reading the code, as well as learners. App->getUser() I think would be better.
    • Got it, $app->User() is calling the function of class "APP", hence it returning the object of User class so we can call methods of User class with it.

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
        ...
        ...
        ...
        ...
    }
}
  • 14
Reply Report

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.

  • 11
Reply Report

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.

  • 7
Reply Report

People seem to be mixing up details of object orientation with encapsulation, which is a much older and wider concept. An encapsulated data structure

  • can be passed around with a single reference, eg increment(myDate) rather than increment(year,month,day)
  • has a set of applicable operations stored in a single program unit (class, module, file etc)
  • does not allow any client to see or manipulate its sub-components EXCEPT by calling the applicable operations

You can do encapsulation in almost any language, and you gain huge benefits in terms of modularisation and maintainability.

  • 3
Reply Report

Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation. Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object. Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions.

<?php
 class YourMarks
  {
   private $mark;
   public Marks
  {
   get { return $mark; }
   set { if ($mark > 0) $mark = 10; else $mark = 0; }
  }
  }
?>

I am giving an another example of real life (daily use) that is “TV operation”. Many peoples operate TV in daily life.

It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel. Here everything is in private except remote so that anyone can access not to operate and change the things in TV.

  • 3
Reply Report
/* class that covers all ATM related operations */
class ATM {

    private $customerId;
    private $atmPinNumber;
    private $amount;

    // Verify ATM card user
    public function verifyCustomer($customerId, $atmPinNumber) {
        ... function body ...
    }

    // Withdraw Cash function
    public function withdrawCash($amount) {
        ... function body ...
    }

    // Retrieve mini statement of our account
    public function miniStatement() {
        ... function body ...
    }
}

In the above example, we have declared all the ATM class properties (variables) with private access modifiers. It simply means that ATM class properties are not directly accessible to the outer world end-user. So, the outer world end-user cannot change or update them directly.

The only possible way to change a class property (data) is a method (function). That’s why we have declared ATM class methods with public access modifier. The user can pass the required arguments to a class method to do a specific operation.

It means users do not have whole implementation details for ATM class. It’s simply known as data hiding.

Reference: http://www.thecreativedev.com/php-encapsulation-with-simple-example/

  • 3
Reply Report

The opposite of encapsulation would be something like passing a variable to every method (like a file handle to every file-related method) or global variables.

  • 2
Reply Report
      • 1
    • Another alternative to encapsulation is inheritance - ie "extend"ing the object containing the data rather than encapsulating it.

Encapsulation: - wrapping of data in single unit. also we can say hiding the information of essential details. Example: You have a mobile phone.... there it some interface which helps u to interact with cell phone and u can uses the services of mobile phone. But the actually working in cell phone is hide. u don't know how it works internally.

  • 2
Reply Report

Simply I prefer that is visibility of your class's property and method. For example- - public - private - protected

Let's take a look real life example for encapsulation.

 class MyClass{
    private $name;

    public function showName($newName){
        $this->name = $newName;
        return $this->name;
    }
 }


 //instantiate object

 $obj = new MyClass();
 echo $obj->showName("tisuchi");

In this case, encapsulation means, we restrict some properties. Like, name property, we can not access from outside of the class. On the other hand, we can access public function entitled showName() with one private parameter.

Simply what I prefer of encapsulation is-

visibility of your property and method.

Although, if you have any intension to understand encapsulation further, I refer to my special tutorial based on encapsulation.

http://tisuchi.com/object-oriented-php-part-3-encapsulation-php/

Hope, it will make your concept more clear. Have fun!

  • 1
Reply Report

In basic terms, it’s the way we define the visibility of our properties and methods. When you’re creating classes, you have to ask yourself what properties and methods can be accessed outside of the class. Let’s say we had a property named foo. If a class extends your class, is it allowed to manipulate and access foo? What if someone creates an instances of your class? Are they allowed to manipulate and access foo?

  • 0
Reply Report

Encapsulation is just how you wanted your objects/methods or properties/variables to be visible in your application. for example, :

class ecap {

public $name;

private $id;

protected $tax;

}

If you want to access private or protected properties, then you have to use getter and setter methods in your class that will be accessible from outside of your class. Meaning, you cannot access your private or protected properties directly from outside of your class but you can use through any methods. Let’s take a look-

in the class, add the following method:

class ecap 
{
 public function userId(){
 return $this->id;
 }
} 

and we can access it like:

 $obj = new ecap();
 echo $obj->userId();
  • 0
Reply Report

Wrapping up of data inside single unit is called encapsulation. Means class members such as method and properties binds together inside a class to avoid accessibility from outside.This is done by making variables and functions of class private.

  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions