views:

1773

answers:

5

What is encapsulation with simple example in php?

+6  A: 

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.

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

?>
fiXedd
+1  A: 

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.

VVS
Another alternative to encapsulation is inheritance - ie "extend"ing the object containing the data rather than encapsulating it.
thomasrutter
+4  A: 

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.

thomasrutter
A: 

yea that is good example by vasanth

vasanth
No, no it isn't.
outis
+1  A: 

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.

Offshore PHP Outsourcing India