Home » Php » What is encapsulation with simple example in php?

What is encapsulation with simple example in php?

Posted by: admin November 30, 2017 Leave a comment

Questions:

What is encapsulation with simple example in php?

Answers:

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

?>

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

encapsulation : Encapsulation is a concept of wrapping up or binding up related data members and methods in a single module known as encapsulation.

here is the proper example of encapsulation

<?php
class person {
    public $name;
    public $age;
    function __construct($n, $a) {
        $this -> name = $n;
        $this -> age = $a;
    }
    public function setAge($ag) {
        $this -> ag = $ag;
    }
    public function display() {
        echo "welcome " . $this -> name . "<br/>";
        return $this -> age - $this -> ag;
    }
}
$person = new person("Pankaj", 25);
$person -> setAge(10);
echo "You are " . $person -> display() . " years old";
?>

Questions:
Answers:

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.

Questions:
Answers:

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
        ...
        ...
        ...
        ...
    }
}

Questions:
Answers:

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.

Questions:
Answers:

Encapsulation is the process of hidding the data of the object from outside world and accessed to it is restricted to members of the class.

Questions:
Answers:

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.

Questions:
Answers:

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!

Questions:
Answers:

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.

Questions:
Answers:

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?

Questions:
Answers:

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