Data encapsulation in PHP 7

Data encapsulation in PHP 7

Data encapsulation in PHP 7



Data encapsulation in PHP 7

What is Data Encapsulation

Data Encapsulation also known as Data Hiding is a very vital object oriented programming concept. In this mechanism user can perform restricted set of operations of the class. So mainly in simple words we set variables to private then they can be used by functions but user cannot change values of those variables directly.





Check Example here



class Employee{

    //Variables

    public $age = '23';
    private $departmentId = 27345;
    public $employeeId = 556752342;


    // Function for changing private value
    public function promotion(){

        return $this->departmentId = 3423;
    }
}

// Creating class Object
$employee = new Employee();

//Setting department id 
$employee->departmentId = 3423;


//displaying department id from function
echo $employee->promotion();

So we can set value





$employee->departmentId = 3423;

If the variable “departmentId” is set to “Public”. But that would be unsafe as any user can change value without any validation. So we set “departmentId” as “Private” and then user only can access this variable using function “permotion”. Now there we can check or validate user before updating “departmentId”. This is how we hide data from user and user needs to be validated before making any change.