PHP | Encapsulation - GeeksforGeeks

10 Oct, 2019
In today’s technical world, maintaining privacy has become one of the demanding needs for the protection of important data. Whenever data modified in one function affects the other functions, it causes a lot of problems in any software. To overcome this problem, object-oriented programming in PHP uses the concept of Encapsulation.
So the OOPs concept of Encapsulation in PHP means, enclosing the internal details of the object to protect from external sources. It describes, combining the class, data variables and member functions that work on data together within a single unit to form an object. Otherwise, its the bundling of properties and behavior in a single class unit.
Data is not accessed directly, in fact, they are accessed through functions(GET or SET) written inside the class. Attributes are kept private but getter(GET) and setter(SET) methods are kept public for manipulation of these attributes.
PHP program for encapsulation: The methods or functions in the following program are update password and check the course name. GFG class defines all the operations related to GFG users.
<?php  // PHP program to implements encapsulationclass GFG {      private $userId;    private $pwd;          // Update GFG password    public function updatePwd($userId, $pwd) {                  // Write function body        echo("Function to update password '"                . $pwd . "' for user " . $userId);                  echo "<br>";    }      // Check account balance    public function courseName($userId) {                  // Write function body        echo("Function to check course name of user "                . $userId);                  echo "<br>";    }}  $obj = new GFG();$obj -> updatePwd('GFG12', 'geeks54321');$obj -> courseName('GFG06');  ?>
Output:
Function to update password 'geeks54321' for user GFG12
Function to check course name of user GFG06

Note: The data members and class properties are not accessible to the outer end-user. So they cannot change the properties.
Program to Access Variables
<?php   class Student {    private $firstname;    private $gender;       public function getFirstName() {        return $this->firstname;    }       public function setFirstName($firstname) {        $this->firstname = $firstname;        echo("First name is set to ".$firstname);        echo("<br>");    }       public function getGender() {        return $this->gender;    }       public function setGender($gender) {        if ('Male' !== $gender and 'Female' !== $gender) {            echo('Set gender as Male or Female for gender');        }           $this->gender = $gender;        echo("Gender is set to ".$gender);        echo("<br>");    }}   $student = new Student();$student->setFirstName('Meena');$student->setGender('Female');   ?>
Output:
First name is set to Meena
Gender is set to Female

Note:
Encapsulation can be used if the properties of the object are private and updating them through public methods.
Encapsulation in PHP can be achieved using the implementation of access specifiers.
It is very careful about OOPs concept of inheritance as many times inheritance can undermine the concept of encapsulation.
Inheritance exposes some details of a parent class, effectively breaking encapsulation.
Advantages of Encapsulation:
Data Hiding and Abstraction: Unnecessary details, internal representation and implementation are hidden from the end-users for protection of data structure and the Class. Data access is prohibited from members of other classes by creating private methods. It protects the internal state of any object by keeping member variables private and preventing any inconsistent state. It is the enclosing of data and related operations into that object.Note: Encapsulation is used to hide internal views from the client.
Note: Encapsulation is used to hide internal views from the client.
Data security: Encapsulation helps in making data very robust and secured, as the data and member functions are wrapped together to form an object. All the tasks are done inside without any external worry and it also makes life very easy.
Reduces complexity: Encapsulation helps in reducing development complexity of the software by hiding the details of implementation and exposing the methods or operations.
Reusability: There are instances, you don’t have to re-write same functionality that you inherited from the parent class.
Reliability: You can make the class read-only or write-only by writing SET or GET methods.
Easier testing of code: Encapsulated PHP code is easy to test as the functions used for testing child class ensures the testing of parent class functions also.
Increased flexibility: Class variables can be accessed by GET or SET methods increasing flexibility. It is easy to maintain as the internal implementation can be changed without changing the code.
Conclusion: Object-oriented programming in PHP is achieved by using the concept of Encapsulation which is used for information hiding. It reduces the easy-accessibility of attributes of the present class. Getter and Setter methods are used for avoiding external unwanted access. It also helps in validating new values assigned to the properties.In short, Encapsulation in PHP is the process of hiding all the secret details of an object that actually do not contribute much to the crucial characteristics of the Class.
PHP-OOP
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Different ways for passing data to view in Laravel
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?