Visibility and Encapsulation
Every property and method in a PHP class can be marked public (reachable from anywhere, the default for methods if you omit a modifier), private (reachable only from inside that exact class, not even a subclass), or protected (reachable from that class and any class that extends it, covered next lesson). Leaving a $balance as public lets any code outside the class rewrite it to anything, bypassing whatever rules the class was supposed to enforce — marking it private and exposing a narrow method instead is how you keep that control.
<?php
class BankAccount {
private float $balance;
public function __construct(float $balance = 0) {
$this->balance = $balance;
}
public function deposit(float $amount): void {
$this->balance += $amount;
}
public function getBalance(): float {
return $this->balance;
}
}
$acc = new BankAccount(100);
$acc->deposit(50);
echo $acc->getBalance(), "\n";
150
private float $balance means no code outside BankAccount — not even $acc->balance from the calling script — can read or overwrite it directly; deposit() and getBalance() are the only sanctioned ways in and out, and deposit() in particular can only ever add to the balance, not replace it with an arbitrary value. : void on deposit() documents that it returns nothing meaningful. Next: inheritance — extends, parent::, and overriding a method.
Practice exercise
Write a Wallet class with a private float $balance (default 0), an add(float $amount) method, and a getBalance() method — then add(25) and echo the balance.