The Wayback Machine - https://web.archive.org/web/20240624000049/https://www.geeksforgeeks.org/php-encapsulation/
Open In App

PHP | Encapsulation

Last Updated : 10 Oct, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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


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.

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



Similar Reads

Encapsulation in JavaScript
Encapsulation is a fundamental concept in object-oriented programming that refers to the practice of hiding the internal details of an object and exposing only the necessary information to the outside world. Encapsulation can be achieved using two techniques: Table of Content Using ClosuresUsing ClassesUsing ClosuresIn JavaScript, closures are func
3 min read
PHP 5 vs PHP 7
PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994. Since its launch in 1994 PHP has become an industry standard supporting almost 80% of the websites ( 79.8% to be precise) with its closest competitor being ASP.Net at 19.8% and others like Ruby, Java trailing far behind. The PHP development team released
4 min read
PHP | Get PHP configuration information using phpinfo()
PHP provides us with a built-in function phpinfo() which gives us the details about the PHP version and PHP configuration of PHP installed in our system. To know about the Configurations and PHP version which is installed in your computer, a simple PHP script can be used. The script consists of a PHP function called "phpinfo()" which outputs inform
2 min read
PHP | php.ini File Configuration
At the time of PHP installation, php.ini is a special file provided as a default configuration file. It's very essential configuration file which controls, what a user can or cannot do with the website. Each time PHP is initialized, the php.ini file is read by the system. Sometimes you need to change the behavior of PHP at runtime, then this config
5 min read
How to import config.php file in a PHP script ?
The include statement in PHP copies the code of text from the file mentioned, into the file that uses the include statement. It directs the preprocessor to insert the content specified into the following program. The name of the file to be included is written in double-quotes. It is a good practice to write the basic database details and user detai
2 min read
How to include content of a PHP file into another PHP file ?
Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file
2 min read
What is New in PHP Type Hinting Support in PHP 8?
PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently. These are the following features used in PHP Type Hitting Support: Table of Content Union TypesMixed TypeStatic Return TypeInheritance of Contravariant ParametersInheritance of P
3 min read
LAMP installation and important PHP configurations on Ubuntu
PHP is the Web development (Server Side Scripting Language) written and developed for web developers.It was developed by Rasmus Lerdorf in 1994, for maintaining his personal homepage. Later he added the feature to communicate with web forms and to connect with databases, named it as Personal Home Page Tools (PHP), Lerdorf wrote those using C binari
5 min read
PHP | imagecreatetruecolor() Function
The imagecreatetruecolor() function is an inbuilt function in PHP which is used to create a new true-color image. This function returns a blank image of the given size. Syntax: resource imagecreatetruecolor( $width, $height ) Parameters: This function accepts two parameters as mentioned above and described below: $width: This parameter is used to s
2 min read
PHP fpassthru( ) Function
The fpassthru() function in PHP is an inbuilt function which is used to read data from a current position from a specified file until end of file and then write the result to the output buffer. The file which has to be read is sent as a parameter to the fpassthru() function and it returns the number of characters passed on success or FALSE on failu
2 min read
Article Tags :
three90RightbarBannerImg