Back to Top

PHP Encapsulation with simple example

Concept of PHP Encapsulation

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.

Encapsulation in PHP

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

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?

  1. Data hiding
  2. Data abstraction

What are the advantages of PHP encapsulation?

  1. 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!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to use _remap function Codeigniter

Posted on 11 years ago

Bhumi

Avoid to use ENUM and SET type in MySQL

Posted on 12 years ago

Bhumi