Encapsulation in PHP is Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Encapsulation in PHP 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.
class YourBag { book();// calling function of book pen();// calling function of pen ReadBook ();// calling function readBook }
Encapsulation means hiding the internal details of an object, i.e. how an object does something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from the other object.
Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public.
So, when you access the property you can validate the data and set it.
Example:
<?php class YourMarks { private $mark; public Marks { get { return $mark; } set { if ($mark > 0) $mark = 10; else $mark = 0; } } } ?>
Below the real life example of encapsulation:
1. Take an example of Mobile Phone and it’s Manufacture:
Let’s take example of Mobile Phone and Mobile Phone Manufacturer
Suppose you are a Mobile Phone Manufacturer and you designed and developed a Mobile Phone design(class), now by using machinery you are manufacturing a Mobile Phone(object) for selling, when you sell your Mobile Phone the user only learn how to use the Mobile Phone but not that how this Mobile Phone works.
This means that you are creating the class with function and by making object (capsule) of it you are making availability of the functionality of you class by that object and without the interference in the original class.
2. 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.