What is Encapsulation in PHP?
Category: Oop
Encapsulation in PHP means restricting direct access to certain parts of an object (like properties) and allowing access only through defined methods. This is done using access modifiers such as public, private, and protected.
class User {
private $password; // Private property – cannot be accessed directly
// Setter method to assign value
public function setPassword($password) {
$this->password = $password;
}
// Getter method to retrieve value
public function getPassword() {
return $this->password;
}
}
$user = new User();
$user->setPassword("secure123");
echo $user->getPassword(); // Output: secure123
✅ Here, the $password property is encapsulated using the private keyword. External code can't access it directly — only through the provided setPassword() and getPassword() methods.
🎯 Why Use Encapsulation in PHP?
- ✅ Improves security by hiding sensitive data
- ✅ Controls data access and validation
- ✅ Enhances maintainability and flexibility
- ✅ Prevents unwanted external modifications