In this article, we are going to learn, what is PHP Encapsulation? What the advantages of PHP Encapsulation? Before we move to the conceptual understanding of encapsulation, we recommend PHP class and object concepts clear in your mind.
What is PHP Encapsulation?
As we know, every PHP class has a property (variable) and behavior (function and method). Combining property and behavior in a single unit class is known as Encapsulation.
Let’s understand encapsulation with some real-time example that plays around us. Now a day, usage of bank ATM is very common. We all are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc.
Have you ever think that what is happening behind all this? The answer you will get is very simple, no. It’s a correct answer. It means that background process was hidden from the end-user or customer, why?
The answer is very simple to make its data secure and robust. In PHP, encapsulation does the same thing to make a code more secure and robust. Using encapsulation, we are hiding the real implementation of data from the end-user.
PHP Encapsulation Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /* class that covers all atm related opetation */ class ATM { private $customerId; private $atmPinNumber; private $amount; // Varify ATM card user public function verifyCustomer($customerId, $atmPinNumber) { ... function body ... } // Withdraw Cash function public function withdrawCash($amount) { ... function body ... } // Retrive mini statement of our account public function miniStatement() { ... function body ... } } |
In the above example, we have declared all the ATM class property (variable) with private access modifier. It simply means that ATM class property is not directly accessible to the outer world end-user. So, the outer world end-user cannot change or update class property directly.
The only possible way to change the class property (data) was a method (function). That’s why we have declared ATM class methods with public access modifier. The user can pass 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.
What are the different terminologies used for PHP Encapsulation?
- Data hiding
- Data abstraction
What are the advantages of PHP encapsulation?
- Make your code secure and robust
Have you used PHP encapsulation in any website? Do you have any more tips? Let me know in the comments!
Did you find this guide useful? Share it with your friends on Facebook, Twitter, and Google Plus!