Tools
Log in
English

Learn to codePHP

PHP encapsulation

Based on PHP 8.3readonly · PHP 8.1+

Hide a bank balance with private and readonly, after seeing the bug it prevents.

In one line

Encapsulation keeps the inside of an object hidden and lets values change only through the methods you choose. PHP hides with private and protected, and readonly locks a value once it is set.

Why you need it

With a public balance, a controller, an admin page or a cron script can all write $acct->balance -= .... If just one of them skips the check, the balance goes negative.

Make the balance private, expose only deposit() and withdraw(), and the rules (no amounts of 0 or less, no overdraft, always log) live in one place. When a rule changes, you edit those two methods.

Everyday picture

Think of a bank counter. Customers cannot reach into the vault; they ask the teller to make a deposit. The teller checks the notes, makes sure there is enough money, and prints a line in the passbook. The vault is the private property; the counter is the method.

The bug you get without encapsulation

<?phpclass Account{    public string $owner;    public int $balance;     public function __construct(string $owner, int $balance)    {        $this->owner = $owner;        $this->balance = $balance;    }} $acct = new Account('Haneul', 30000);$acct->balance -= 45000;$acct->owner = 'nobody';echo "{$acct->owner}: {$acct->balance}\n";

When you run it

nobody: -15000

Every property is public, so taking 45000 out of a 30000 account goes straight through. Nothing stops the balance from reaching -15000.

Any line can even rename the owner, here to nobody. Once lines like these are spread across controllers, finding the one that broke the balance can eat a whole day.

Example code

main.php · 63 lines
<?phpdeclare(strict_types=1); final class Account{    private int $balance = 0;    private array $log = [];     public function __construct(        public readonly string $owner,        int $opening,    ) {        $this->deposit($opening);    }     public function deposit(int $amount): void    {        if ($amount <= 0) {            throw new InvalidArgumentException("deposit must be positive: $amount");        }        $this->balance += $amount;        $this->log[] = "+$amount";    }     public function withdraw(int $amount): void    {        if ($amount > $this->balance) {            throw new DomainException("not enough money: $amount > {$this->balance}");        }        $this->balance -= $amount;        $this->log[] = "-$amount";    }     public function balance(): int    {        return $this->balance;    }     public function history(): array    {        return $this->log;    }} $acct = new Account('Haneul', 30000);$acct->withdraw(12000);try {    $acct->withdraw(45000);} catch (DomainException $e) {    echo 'Refused: ', $e->getMessage(), "\n";}try {    $acct->deposit(-500);} catch (InvalidArgumentException $e) {    echo 'Refused: ', $e->getMessage(), "\n";}try {    $acct->owner = 'nobody';} catch (Error $e) {    echo 'Blocked: ', $e->getMessage(), "\n";}echo "{$acct->owner}: {$acct->balance()}\n";echo 'History: ', implode(', ', $acct->history()), "\n";

When to use it

  • A value has rules (never negative, a maximum length, dates in order)
  • Changing a value must also trigger something, such as a log entry or a notification
  • A value must never change after it is set (owner name, order number), which is what readonly is for

readonly properties arrived in PHP 8.1 and readonly class in 8.2. PHP 8.4 adds asymmetric visibility such as public private(set) int $balance, which opens reading and writing to different callers (new in 8.4, not available in 8.3).

Common mistakes

Reading a private property from outside

private is visible inside the class only. Outside code cannot even read it, so offer a method such as balance() when reading should be allowed. That method can also convert units or check permissions.

Wrong

$acct = new Account('Haneul', 30000);echo $acct->balance, "\n";

When you run itFatal error: Uncaught Error: Cannot access private property Account::$balance

Fixed

$acct = new Account('Haneul', 30000);echo $acct->balance(), "\n";

When you run it30000

Handing out an object stored in a private property

Even behind private, returning the inner DateTime lets the caller change that very object. Arrays are copied, objects are shared. With the unchangeable DateTimeImmutable, modify() leaves the original alone and returns a new object. Otherwise return a clone.

Wrong

final class Booking{    public function __construct(private DateTime $day)    {    }     public function day(): DateTime    {        return $this->day;    }} $b = new Booking(new DateTime('2026-05-01'));$b->day()->modify('+7 days');echo $b->day()->format('Y-m-d'), "\n";

When you run it2026-05-08

Fixed

final class Booking{    public function __construct(private DateTimeImmutable $day)    {    }     public function day(): DateTimeImmutable    {        return $this->day;    }} $b = new Booking(new DateTimeImmutable('2026-05-01'));$later = $b->day()->modify('+7 days');echo $b->day()->format('Y-m-d'), ' / ', $later->format('Y-m-d'), "\n";

When you run it2026-05-01 / 2026-05-08

A setter that accepts anything

Hiding the property and then letting setBalance() take any value is no better than public. Name methods after what they do (deposit, withdraw) and refuse bad values inside them.

Wrong

final class Wallet{    private int $balance = 0;     public function setBalance(int $value): void    {        $this->balance = $value;    }     public function balance(): int    {        return $this->balance;    }} $w = new Wallet();$w->setBalance(-999);echo $w->balance(), "\n";

When you run it-999

Fixed

final class Wallet{    private int $balance = 0;     public function deposit(int $amount): void    {        if ($amount <= 0) {            throw new InvalidArgumentException('deposit must be positive');        }        $this->balance += $amount;    }     public function balance(): int    {        return $this->balance;    }} $w = new Wallet();try {    $w->deposit(-999);} catch (InvalidArgumentException $e) {    echo $e->getMessage(), "\n";}echo $w->balance(), "\n";

When you run itdeposit must be positive 0

Check yourself

Question 1

With the example Account, what does $acct->balance = 0; from outside do?

Show the answer

Answer: 2. It throws an `Error` A private property can be neither read nor written from outside. PHP throws an Error at once and the balance is untouched.

Question 2

A line is added to the array returned by history(). How many lines does the account log hold?

$acct = new Account('Joon', 500);$h = $acct->history();$h[] = '+999999';echo count($acct->history()), "\n";

Show the answer

Answer: 1. 1 PHP arrays are copied when passed around. The new line goes into the copy in $h, so the account still holds just the opening deposit.

Questions people ask

Can a private property not even be read from outside?

Right. Reading and writing both throw an Error. Offer a method such as balance(), or make it public readonly, when reading should be allowed.

How is readonly different from private?

private decides who can see a property; readonly decides whether it can change after it is set. public readonly means everyone reads it and nobody changes it.

Should I write getters and setters for everything?

No. A setter that accepts anything is the same as a public property. Name methods after what they do, like deposit and withdraw, and check values there.