Encapsulation is a fundamental topic in Object-Oriented Programming (OOP). It states the concept of binding data (attributes) and methods (functions) into a single unit (Class). This term is also referred to as Information Hiding.
Scenario : The data was stored in one single location and it was modified from every location wherever it was called, which caused many problems as data modified in one function would affect the other functionality too. So to overcome this issue OOP uses Encapsulation in PHP. Let’s see what encapsulation is all about.
Encapsulation achieved by making data and methods of class private. It solves the problem at the implementation level rather than at the design level.
Encapsulation is specifically used for protection. It is the process of hiding the data of the object from other classes/methods and access to the data is prohibited to the members of the class.
If you have an attribute that cannot be seen by others and you bundle it with functions or methods which provide all the access to the data members, then you can hide the content and control access to the object.
Users will be unaware of the inner implementation and will only get to know the upper or the top view of the functionality as to how the class is storing the data into variables. The functions of an object can access the functions of other objects.
Benefits of Encapsulation in PHP
- Encapsulation helps us in binding the data (variables/attributes) and the member functions of a class.
- The fields of the class can be made read-only or write-only using access specifiers such as public, private and protected.
- It provides your code more security, flexibility and easy to maintain.
- Encapsulation prevents unexpected changes in the data.
- Using Encapsulation, your methods and data attributes cannot be called directly hence no illegal data access by users.
- It allows us to modify the implemented code without breaking the logic/code of others who use the same code and functions.
- The user of the class doesn’t know how the class stores the data.
- Encapsulation also improves the re-usability and it is easy to change with new requirements or needs.
- It provides the integrity of an object’s data.
The importance of encapsulation is to hide the complex code from the user and show the real functionality to the user. If proper encapsulation is not followed in the code, it leads to its bad designing. Thus, it is reflected by the fact that most of the modern programming languages support encapsulation.