PHP OOP Encapsulation
Encapsulation is a fundamental concept in Object-Oriented Programming (OOP), and it is used to bundle the data (properties) and the methods (functions) that operate on that data into a single unit, called a class. In PHP, encapsulation is primarily implemented through the use of access modifiers, which control the visibility and accessibility of the properties and methods.
What is Encapsulation?
- Encapsulation means restricting access to certain details of an object and exposing only what is necessary. It helps protect the internal state of an object and ensures that objects are manipulated only in allowed ways.
- Encapsulation allows a class to hide its internal data and behavior while exposing only specific methods to interact with it.
Access Modifiers in PHP
PHP has three access modifiers that control how properties and methods can be accessed:
public: Properties and methods declared as
public
can be accessed from anywhere, both inside and outside of the class.protected: Properties and methods declared as
protected
can only be accessed within the class itself, by derived classes (i.e., subclasses), or within classes in the same inheritance chain.private: Properties and methods declared as
private
can only be accessed within the class itself and not by any outside code or derived classes.
Example of Encapsulation
Here is a simple example that demonstrates encapsulation in PHP:
class BankAccount {
private $balance;
public function __construct($initialBalance) {
if ($initialBalance < 0) {
throw new Exception("Initial balance cannot be negative.");
}
$this->balance = $initialBalance;
}
// Public method to deposit money
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
} else {
throw new Exception("Deposit amount must be positive.");
}
}
// Public method to withdraw money
public function withdraw($amount) {
if ($amount > $this->balance) {
throw new Exception("Insufficient balance.");
}
$this->balance -= $amount;
}
// Public method to get the balance (read-only access)
public function getBalance() {
return $this->balance;
}
}
// Using the class
$account = new BankAccount(100);
$account->deposit(50);
$account->withdraw(30);
echo "Balance: " . $account->getBalance(); // Outputs: Balance: 120
Explanation
Private Property (
$balance
):- The
balance
property is declared asprivate
, meaning it cannot be accessed directly from outside the class. - This helps ensure that the balance can only be modified in controlled ways through the class methods.
- The
Public Methods (
deposit
,withdraw
,getBalance
):- Methods like
deposit
,withdraw
, andgetBalance
provide controlled access to thebalance
. deposit()
andwithdraw()
enforce specific business rules, such as only allowing positive deposits and ensuring that withdrawals do not exceed the available balance.getBalance()
allows read-only access to thebalance
, meaning users can check the balance but cannot modify it directly.
- Methods like
Benefits of Encapsulation
Control Access to Data: Encapsulation allows you to control who can see or modify the properties of an object. In the example above, the balance is only modified through methods that have built-in validation.
Data Integrity: By restricting direct access to properties, you can ensure the object maintains a valid state. For example, preventing the balance from becoming negative helps maintain data integrity.
Code Maintainability: Encapsulation makes your code more maintainable. If the internal implementation of a class changes, you only need to update the internal methods without changing how other parts of the application interact with the class.
Flexibility: You can provide a specific interface for users of the class without exposing internal implementation details. This makes it easier to make changes to the class without affecting external code.
Getter and Setter Methods
Getter and setter methods are often used as a way to encapsulate private properties. These methods provide controlled access to class properties.
- Getter Method: Used to retrieve (read) the value of a private property.
- Setter Method: Used to set (modify) the value of a private property with additional validation or logic.
class Product {
private $price;
public function setPrice($price) {
if ($price < 0) {
throw new Exception("Price cannot be negative.");
}
$this->price = $price;
}
public function getPrice() {
return $this->price;
}
}
$product = new Product();
$product->setPrice(100);
echo $product->getPrice(); // Outputs: 100
Visibility of Methods
In addition to properties, encapsulation also applies to methods. You can have:
- Public methods: These are part of the class’s interface and can be called from anywhere.
- Protected methods: These can be used by the class itself and its subclasses, allowing shared behavior without exposing it to external users.
- Private methods: These can only be called by the class itself, not even by subclasses, which is useful for helper methods meant for internal class logic.
Example of Method Encapsulation
class Employee {
private $salary;
public function __construct($initialSalary) {
$this->salary = $initialSalary;
}
public function increaseSalary($amount) {
$this->validateSalaryIncrease($amount);
$this->salary += $amount;
}
public function getSalary() {
return $this->salary;
}
// Private helper method
private function validateSalaryIncrease($amount) {
if ($amount < 0) {
throw new Exception("Salary increase must be positive.");
}
}
}
$employee = new Employee(5000);
$employee->increaseSalary(500);
echo $employee->getSalary(); // Outputs: 5500
- Private Method (
validateSalaryIncrease
): This helper method is private, meaning that it is only used within the class itself and ensures that the salary increase is positive. This prevents direct access to validation from outside the class.
Summary
- Encapsulation is about bundling data (properties) and the methods that operate on that data into a class, while restricting access to the internal representation of that data.
- Access Modifiers (
public
,protected
,private
) control the visibility of properties and methods. - Getter and Setter Methods provide controlled access to private properties, often including validation logic.
- Encapsulation protects the internal state of an object, maintains data integrity, and ensures controlled access to the object's properties and methods.
Encapsulation is a powerful concept in PHP OOP that allows you to create robust, secure, and well-structured classes, providing a clear interface while protecting the internal workings of your objects.