×

php · level 3 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

private keeps the inside of an object behind a locked door.

Every property and method has a . public means any code can reach it. private means only code inside the same class can. Outside code that tries gets an Error.

Why hide things? A piggy bank should never hold minus five pounds. If $pence were public, any line anywhere could set it. Make it private, and the only way in is through methods that check the rules first. That is .

To let others read a private value, add a : a public method that returns it.

<?php
class PiggyBank {
    private int $pence = 0;

    public function add(int $amount): void {
        if ($amount > 0) {
            $this->pence = $this->pence + $amount;
        }
    }

    public function balance(): int { return $this->pence; }
}
$bank = new PiggyBank();
$bank->add(250);
$bank->add(-900);
echo $bank->balance() . "p saved\n";

The minus 900 is quietly refused, because the only way to change $pence checks the amount first.