PHP | Encapsulation

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// PHP program to implements encapsulation
class 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');
  
?>

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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');
   
?>

chevron_right


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.

  • 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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.