What is Encapsulation

Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It refers to the bundling of data (attributes) and methods (functions) that operate on that data into a single unit or class. The primary purpose of encapsulation is to restrict direct access to some of an object's components, which can prevent the accidental modification of data. This is achieved through access modifiers like private, protected, and public.

In encapsulation, we often use getter and setter methods to access and update the values of private variables, providing a controlled way to modify the data.

<?php class Person { private $name; private $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getAge() { return $this->age; } public function setAge($age) { if ($age > 0) { $this->age = $age; } } } $person = new Person("John", 25); echo $person->getName(); // Outputs: John ?>

encapsulation object-oriented programming OOP data protection access modifiers