CodeBlanks Logo Icon CodeBlanks

Encapsulation

PHP course · Intermediate · Lesson 27/115

Learn to make internal state private and provide controlled access from outside.

Encapsulation

Encapsulation means hiding an object's internal state from the outside and providing controlled access through methods. The main tool is private visibility.

For example, in a BankAccount class you make balance private. Nobody outside can write $account->balance = -1000 directly. The balance can only change via methods like deposit() or withdraw(), which enforce checks such as no negative amounts or insufficient funds.

This keeps the object in a consistent state. Encapsulation exposes a clean interface, hides internal details, and lets you manage changes in one place.

Encapsulation example: BankAccount

Let's see the power of encapsulation with an example:

  • The balance property is declared as private int $balance = 0;.
  • The deposit(int $amount) method checks $amount > 0 and adds $this->balance += $amount.
  • The getBalance() method reads the current balance.

Outside code cannot write $account->balance. The only way to change the balance is deposit(), which rejects negative amounts. So the balance can never go negative; the class's invariant is preserved.

Exercise Encapsulated BankAccount class

Define a BankAccount class with a private int $balance = 0 property. A public function deposit(int $amount): void method does $this->balance += $amount. A public function getBalance(): int method does return $this->balance. Then create $account = new BankAccount(), call $account->deposit(100) and $account->deposit(50), and print echo $account->getBalance() . "\n".

Show example solution
Declare private $balance, deposit does $this->balance += $amount, getBalance returns $this->balance.
Example solution:
<?php
// Define a BankAccount class with encapsulation
class BankAccount {
    private int $balance = 0;
    public function deposit(int $amount): void {
        $this->balance += $amount;
    }
    public function getBalance(): int {
        return $this->balance;
    }
}
$account = new BankAccount();
$account->deposit(100);
$account->deposit(50);
echo $account->getBalance() . "\n";

Test yourself

  1. What does encapsulation provide?

    • All properties accessible from everywhere
    • Hiding internal state with controlled access
    • A class being inherited by subclasses
    • A class having multiple parents
    Show answer

    Hiding internal state with controlled access — Correct. Encapsulation makes internal state private and exposes controlled methods.

  2. Match the encapsulation example

    Encapsulation
    Hiding internal state
    private $balance
    Not writable outside
    deposit()
    Adds to balance
    getBalance()
    Reads balance
  3. Encapsulation pattern: private balance

    class BankAccount {
        ____
    }
    Show answer
    class BankAccount {
        private $balance;
    }

All lessons in Intermediate