Encapsulation in PHP with Examples
Encapsulation is one of the most important concepts in object-oriented programming (OOP) in PHP. It is the process of binding data (variables) and methods (functions) together into a single unit called class.
Encapsulation restricts direct access to an object’s properties and methods, and provides a controlled interface to interact with that object. In simple terms,
Encapsulation = Data Protection + Controlled Access
In PHP, encapsulation helps maintain the integrity and consistency of an object’s data by hiding the internal details and providing controlled access through the public getter and setter methods.
This ensures that external code cannot directly modify the object’s properties and allows you to implement validation and business logic inside getter and setter methods. Using encapsulation, you can write more modular, maintainable, and secure code.
Real-World Examples of Encapsulation in PHP
Here are some simple, practical examples from everyday life that will help you to understand the basic concept of encapsulation in PHP:
1. ATM Machine
When you use an ATM machine, you enter your PIN and choose withdrawal, balance inquiry, etc. You cannot see or modify the internal code, logic, or data of ATM. You use only the public interface (buttons, display).
Your account details and banking logic are protected internally. This is exactly how encapsulation works—the internal data is hidden, and only controlled access is provided.
2. Mobile Phone
You daily use your mobile phone. You use:
- Calling
- Messaging
- Apps
- Camera, etc.
But you cannot access the internal system files, hardware circuits, or inter-process communication. The phone only provides interfaces (apps, buttons) while hiding internal logic. This is a perfect example of encapsulation in your daily life.
Why Encapsulation Is Important in PHP?
Encapsulation helps to:
- Improve code security
- Sensitive data cannot be accessed directly from outside the class.
- Prevent accidental changes
- Variables remain protected from unintended modifications.
- Promote maintainability
- Internal logic can be changed without affecting the external code.
- Provide controlled access using getters and setters
- You decide how data is accessed, updated, or restricted.
- Implement data validation inside the class
- Ensures proper and safe data handling in real-time applications such as login systems, forms, APIs, banking, etc.
How to Achieve Encapsulation in PHP?
You can achieve encapsulation in PHP using the following three steps:
1. Declare variables as private/protected to prevent direct access from outside the class. The private access modifier is accessible only within the class, while protected modifier is accessible within the class and child classes. This hides the data from external access.
2. Use public getter and setter methods to provide controlled access. This is because the private/protected properties cannot be accessed directly from outside the class. Getter and setter methods act as public interfaces to access internal data safely.
3. Add validation inside setter methods if necessary, because setters are the best place to validate data before storing it. This ensures accuracy and protects the integrity of the object’s data.
What is a Setter Method in PHP?
A setter method in PHP allows you to assign or update the value of a given private/protected property. The basic syntax to define a setter method is as:
public function setPropertyName($value) {
$this->propertyName = $value;
}
In this syntax,
- setPropertyName → This specifies the method name.
- $value → This is the parameter to accept new value.
- $this->propertyName → This assigns the value to the class variable.
What is a Getter Method in PHP?
A getter method allows you to retrieve or return the value of a given private/protected property. The basic syntax to define a getter method in PHP is as:
public function getPropertyName() {
return $this->propertyName;
}
In the above syntax,
- getPropertyName → This specifies the method name.
- return → This sends the internal value back to the caller.
Basic Example of Getter and Setter in PHP
<?php
class Student {
private $name;
// Define a setter method.
public function setName($name) {
$this->name = $name;
}
// Define a getter method.
public function getName() {
return $this->name;
}
}
// Create an object of class Student.
$stu = new Student();
// Passing the value to the setter method.
$stu->setName("Saanvi");
// Calling getter method using reference variable to retrieve the value of the variable.
echo $stu->getName();
?>
Output:
Saanvi
In this example, we created a class named Student that contains a private property $name. Because the property is private, you cannot access it directly from outside the class. To access and modify the private property, we have created a getter and setter methods within the class. These methods provide the controlled access to the property.
Outside the class, we have created an object of class Student. The setter method is used to set the value of the $name property, and the getter method is used to retrieve and display that value.
This demonstrates the core idea of encapsulation in PHP: the data is hidden because of private, and access is provided only through controlled public methods.
Example of Encapsulation in PHP
Let’s take some important examples based on the concepts of encapsulation in PHP that you should practice them.
Example 1: Without Encapsulation (Bad Practice)
<?php
class Student {
public $name; // Public property
}
$stu = new Student();
// Directly accessing and modifying the property $name.
$stu->name = "Saanvi";
echo $stu->name;
?>
Output:
Saanvi
In this example, we have defined a class Student, which contains a public property (variable) $name. Since it is public, anyone can directly access and modify from anywhere in the program. This means there is no control, no validation, and no protection over the value stored in $name.
Anyone can assign any type of value, even an invalid one. For example:
$stu->name = 12345; // Invalid name
This makes the code unsafe, error-prone, and difficult to maintain, especially in larger applications. Directly exposing properties violates encapsulation and goes against the core principles of PHP object-oriented programming (OOP). Therefore, this approach should be avoided.
Example 2: With Encapsulation (Good Practice)
<?php
class Student {
private $name; // Private property so, it is hidden from outside the class.
// Define a setter method to set the value.
public function setName($name) {
// Validation
if (is_string($name) && strlen($name) > 1) {
$this->name = $name;
} else {
echo "Invalid name!";
}
}
// Define a setter method to retrieve the value.
public function getName() {
return $this->name;
}
}
$stu = new Student();
// Call setter method to assign value.
$stu->setName("Saanvi");
// Call getter method to retrieve value.
echo $stu->getName();
?>
Output:
Saanvi
As you can see in this example, we have declared the variable $name as private, so no anyone can access it directly from outside the class. This hides the internal data from outside the class.
Inside the class, we have defined a setter method to set the value of the variable $name. Inside the setter method, we validates the data to prevent invalid data. Validation only allows proper string names.
After that, we have defined a getter method to retrieve the stored value of $name. The getter and setter methods provide safe, controlled access to the private property (variable).
Outside the class, we called variable $name and assigned the value to it.
$stu->setName("John");You cannot do this:
$stu->name = "John"; // Not allowed
This enforces controlled access and data safety. Hence, encapsulation ensures:
- Data protection
- Controlled access
- Better security
- Cleaner and maintainable code
- No accidental or unauthorized modifications
Without Encapsulation vs With Encapsulation
| Feature | Without Encapsulation | With Encapsulation |
|---|---|---|
| Data Protection | None | Strong |
| Access to Variables | Direct access | Controlled via methods |
| Validation | No | Yes |
| Security | Low | High |
| Maintainability | Poor | Excellent |
| OOP Compliant | No | Yes |
Example 2: Encapsulation With Validation
<?php
class Person {
private $age;
public function setAge($age) {
if ($age < 0) {
echo "Invalid age! \n";
} else {
$this->age = $age;
}
}
public function getAge() {
return $this->age;
}
}
$p = new Person();
$p->setAge(-5); // Invalid age.
$p->setAge(25);
echo $p->getAge();
?>
Output:
Invalid age! 25
Example 3: Using Protected Members (Inheritance + Encapsulation)
<?php
class BankAccount {
protected $balance = 0;
protected function depositAmount($amount) {
$this->balance += $amount;
}
}
// Creating a subclass.
class UserAccount extends BankAccount {
public function deposit($amount) {
$this->depositAmount($amount);
}
public function getBalance() {
return $this->balance;
}
}
// Creating an object of subclass UserAccount.
$acc = new UserAccount();
$acc->deposit(2000);
echo $acc->getBalance();
?>
Output:
2000
In this example, the variable $balance is protected. Therefore, child class can access it. The depositAmount() method is protected to avoid misuse. Public methods provide controlled access.
Example 4: Encapsulation with Read-Only Property
If you define only a getter method and do not provide a setter method, the property becomes effectively read-only from outside the class. Since the property is private (or protected), its value can be assigned only inside the class or usually inside the constructor. External code cannot modify it. This is a standard and recommended way to implement read-only encapsulation in PHP.
<?php
class Product {
private $price = 1000;
// Define getter method to make read-only.
public function getPrice() {
return $this->price;
}
}
$p = new Product();
echo $p->getPrice();
?>
Output:
1000
Example 5: Encapsulation with Write-Only Property
If you define only a setter method and do not provide a getter method, the property becomes effectively write-only from outside the class. Since the property is private (or protected), external code cannot read or retrieve its value. It can only assign or update the value using the setter.
<?php
class User {
private $password;
// Define Setter only (write-only property).
public function setPassword($pass) {
// Validation
if (strlen($pass) < 6) {
echo "Password must be at least 6 characters long. \n";
return;
}
// Value is stored but not readable from outside.
$this->password = $pass;
echo "Password set successfully.";
}
}
$user = new User();
$user->setPassword("123"); // Too short
$user->setPassword("secure123"); // Valid
// Trying to read $password will give an error
// echo $user->password; // Not allowed
// echo $user->getPassword(); // No getter provided
?>
Output:
Password must be at least 6 characters long. Password set successfully.
In this example, we have defined a class User, which contains a private $password property and a setter method setPassword(). There is no getter method, so you cannot retrieve the password from outside the class. Code outside the class can write the password but cannot read it because it is write-only.
Advanced Example 6: Encapsulation in Login System
<?php
class Login {
private $email;
private $password;
public function setEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email! \n";
return;
}
$this->email = $email;
}
public function setPassword($password) {
if (strlen($password) < 6) {
echo "Password too short!";
return;
}
$this->password = password_hash($password, PASSWORD_DEFAULT);
}
public function getInfo() {
return "Email: {$this->email}, Hashed Password: {$this->password}";
}
}
$user = new Login();
$user->setEmail("invalidEmail");
$user->setEmail("user@gmail.com");
$user->setPassword("123");
$user->setPassword("strongPass");
echo $user->getInfo();
?>
Output:
Invalid email! Password too short! Email: user@gmail.com, Hashed Password: $2y$10$Bj8x5VUuIViQm8gLeFTqLuvTWHtsTMdTg0PhwYAoDXqwBo2nr7VoC
Advantages of Encapsulation in PHP
There are the following advantages of encapsulation in PHP:
- Encapsulation provides data protection by preventing unauthorized access to internal properties.
- It makes the code maintenance easy because internal changes don’t break external code that uses the class.
- It allows better controlled data modification through getter and setter methods.
- Encapsulation improved security by providing authentication, validation, and other sensitive operations inside the class.
- It prevents direct modification of properties, ensuring data integrity and reducing bugs.
Best Practices for Using Encapsulation in PHP
Here, we have listed some key points for using encapsulation in PHP that you should keep in mind:
- Always keep sensitive data private.
- Use getter and setter methods for controlled access. Never expose properties directly.
- Add validation inside setter method.
- Always use meaningful method names. For example, setPrice() and getPrice() methods make your code readable.
- Use private methods for calculations and sensitive operations.
Conclusion
Encapsulation is the process of hiding internal data and functionality from outside access. It is one of the fundamental principles of PHP OOP that restricts direct access to an object’s properties and methods. We achieve encapsulation by declaring properties as private or protected and providing controlled access through getter and setter methods.
This ensures data protection, controlled modification, maintainable, and secure code. We hope you now clearly understand how to implement encapsulation in PHP and have practiced the basic to advanced examples discussed.


