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.
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.
Press Run to try your edited code right away. The step-through and the output above follow the original code.
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.
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.
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.
finalclassWallet{privateint$balance = 0;publicfunctiondeposit(int$amount): void {if ($amount <= 0) {thrownewInvalidArgumentException('deposit must be positive'); }$this->balance += $amount; }publicfunctionbalance(): int {return$this->balance; }}$w = newWallet();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?
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.