Encapsulation in OOP

Ghulam Mujtaba - Jul 27 - - Dev Community

Encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that binds together the data and the methods that manipulate that data, keeping both safe from outside interference and misuse.

In PHP, encapsulation is achieved by using classes and objects to wrap data (properties) and methods that operate on that data. This helps to:

  • Hide internal implementation details

  • Protect data from external interference

  • Improve code organization and structure

  • Enhance data security and integrity

How to achieve encapsulation in OOP php?

To achieve encapsulation in PHP, we can use:

  • Access modifiers (public, protected, private) to control access to properties and methods

  • Constructors to initialize objects

  • Getters and setters to access and modify properties

<?php 

class BankAccount {
    private $balance;

    public function __construct($initialBalance) {
        $this->balance = $initialBalance;
    }

    public function getBalance() {
        return $this->balance;
    }

    public function deposit($amount) {
        $this->balance += $amount;
    }

    public function withdraw($amount) {
        if ($amount <= $this->balance) {
            $this->balance -= $amount;
        }
    }
}

$account = new BankAccount(1000);
echo $account->getBalance(); // Outputs: 1000
$account->deposit(500);
echo $account->getBalance(); // Outputs: 1500
$account->withdraw(200);
echo $account->getBalance(); // Outputs: 1300
Enter fullscreen mode Exit fullscreen mode

In this example, the BankAccount class encapsulates the $balance property and provides methods to interact with it, while hiding the internal implementation details.

I hope that you have clearly understood it.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player