Encapsulation in PHP with Example
Today we going to explore what is Encapsulation in PHP and how to use it.
Few things we need to know about Encapsulation.
Encapsulation => Enclose within a capsule
Encapsulation allows a class to provide signals to the outside world that certain internals are private and shouldn’t be accessed.
So at it’s core, encapsulation is about communication.
Encapsulation is the ability of an object to hide parts of its state and behaviors form other objects, exposing only a limited interface to the rest of the program.
Let’s see some basic code example
class Person
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
public function name()
{
return $this->name;
}
public function job()
{
return 'Web developer';
}
protected function salary()
{
return 'can\'t expose';
}
private function girlFriend()
{
return 'can\'t expose';
}
}
$jhon= new Person('John Doe');
var_dump($jhon->name); // It's public
var_dump($jhon->salary); // It's Encapsulated so can't access
Here some real life code example
class BankAccount {
private $accountNumber;
private $balance;
public function __construct($accountNumber, $initialBalance) {
$this->accountNumber = $accountNumber;
$this->balance = $initialBalance;
}
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
echo "Deposited $amount. New balance: $this->balance\n";
} else {
echo "Invalid deposit amount\n";
}
}
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
echo "Withdrawn $amount. New balance: $this->balance\n";
} else {
echo "Invalid withdrawal amount\n";
}
}
public function getBalance() {
return $this->balance;
}
}
// Create a new bank account
$account = new BankAccount('123456789', 1000);
// Accessing public methods to interact with the account
$account->deposit(500);
$account->withdraw(200);
echo "Current balance: $".$account->getBalance()."\n";
// Attempting to access private properties directly (will result in an error)
// echo $account->accountNumber; // This line will produce an error
// echo $account->balance; // This line will produce an error
In summary, encapsulation is a fundamental concept in OOP that brings numerous benefits, including improved security, code organization, maintainability, and reusability. It helps you build robust, modular, and maintainable software by controlling access to an object’s internal state and providing well-defined interfaces for interacting with that state.
For more details of OOP (Object Ordinated Programming) , you may have a look at the link given below. Feel free to leave a comment if you have any feedback or questions.
https://github.com/mohasin-dev/Object-Oriented-Programming-in-PHP
Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP