EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Encapsulation in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Encapsulation in PHP

Encapsulation in PHP

Introduction to Encapsulation in PHP

The following article Encapsulation in PHP provides a detailed outline for PHP encapsulation.

  • In earlier days, the computer programs were a long sequence of commands. The commands were then clubbed into the list of commands called the functions.
  • All 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 is a fundamental topic in Object-Oriented Programming Language (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.
  • This is 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.
  • In our day to day life, encapsulation is like our wardrobe where we can keep our shirts, pants, etc. In this case, the wardrobe will be the main class and the attributes will be clothes, boxes, etc.

How Does Encapsulation Work in PHP?

  • As we all know encapsulation is used to hide the details from users. To achieve this, we create the object of a class and the object calls the methods and methods perform their task with defined properties.
  • Let’s take an example of an Air Conditioner and Air Conditioner Manufacturer
    Suppose you are an Air Conditioner Manufacturer and you have designed and integrated an Air Conditioner design (class), now by using your equipment you are manufacturing an Air Conditioner (object) for selling purpose, when you sell your Air Conditioner the user needs to know how to use an Air Conditioner instead of that how it works OR let’s assume you have a laptop and there is an interface for you to interact with it, you will use the services of the laptop instead of knowing how it actually works.
  • This means that you are creating the class with functions and by making objects of the class you are making availability of the functionality of your class by that object and without the interference in the original class.
  • Encapsulation is just how you wanted your objects or variables to be visible in your implemented code.

Example

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

class employee { public $name; private $id; protected $tax; public $age; }

If you have to access private/protected properties, you can use getter and setter methods in your class.

As the name states,

  1. The getter method retrieves an attribute in other classes.
  2. The setter method modifies/changes the value of the attribute/data.
  • Depending on the methods that we implement, we can decide what permissions have to be given. We can give read-only, write-only, full permissions or no permissions at all. To achieve this we use access specifiers such as public, private and protected.
  • You can use public property anywhere inside the class as well as outside the class, but you cannot use private and protected properties outside the class directly by calling it. Private methods can be accessed within the same class and protected methods can be accessed only by the subclasses. Outside, the class can’t access private or protected method of other classes.
  • Using getter and setter methods, you can access the variables and methods outside the class as well. Take a look at the employee class, in the class, add the following method

class employee{ public function employee_ID(){ return $this->id; }}

And we can access by calling the function like this

$obj = new employee(); echo $obj->employeeID()

Example of Encapsulation in PHP

Following is an example:

Implemented Code:

<!DOCTYPE html>
<html>
<head>
<title> Encapsulation in PHP </title>
</head>
<body>
<?php
class Employee
{
public $employee_name;
public $employee_id;
function __construct($emp_name, $emp_id)
{
$this->employee_name = $emp_name;
$this->employee_id = $emp_id;
}
public function Employee_details()
{
echo "Employee name is $this->employee_name and Employee id is $this->employee_id";
}
}
$obj = new Employee("Abhishek", "123456");
echo $obj->Employee_details();
?>
</body>
</html>

Output:

Output 1

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.
  • 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.
  • It provides the integrity of an object’s data.
  • The user of the class doesn’t know how the class stores the data.
  • Encapsulation prevents unexpected changes in the data.
  • Encapsulation also improves the re-usability and it is easy to change with new requirements or needs.

Conclusion

In this article, we learned one of the most important object-oriented programming concepts. Encapsulation is one of the most famous and commonly used techniques to overcome the functions and methods that are called in multiple locations.

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 such as PHP, JAVA, etc.

Recommended Articles

This is a guide to Encapsulation in PHP. Here we discuss the Introduction, Working, Examples, and Benefits of Encapsulation in PHP. You may also look at the following articles to learn more –

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)
  1. What is PHP?
  2. Encapsulation in C++
  3. Encapsulation in C
  4. Encapsulation in JavaScript

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More