0% complete

Object-Oriented PHP · Lesson 9 of 14

Encapsulation

Protect internal state and expose safe operations.

Lesson

Encapsulation hides implementation details and makes valid state easier to maintain. Private properties and methods restrict access to the class; public methods form its contract. Avoid adding getters and setters mechanically—expose operations that represent meaningful domain behavior. This account prevents a withdrawal that would make its balance negative. Further guidance Give an object one clear responsibility and protect state that must satisfy a rule. Prefer a small public contract and composition for replaceable collaborators; use inheritance only for a genuine subtype. Test behavior through public methods instead of relying on internal implementation details. Practice task: Create a fresh example for Encapsulation. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Encapsulation
PHP
class Account
{
    public function __construct(private int $balance) {}
    public function balance(): int { return $this->balance; }
    public function deposit(int $amount): void
    {
        if ($amount > 0) $this->balance += $amount;
    }
}
$account = new Account(100);
$account->deposit(25);
echo $account->balance();
Expected output
125

Key points

  • Protect internal state and expose safe operations.
  • Protect object invariants behind a small public API.
  • Prefer composition unless inheritance expresses a genuine subtype.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.