php · level 3 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
One line asks politely, one does not. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
class Secret {
private string $code = "1234";
public function hint(): string {
return "It has " . strlen($this->code) . " digits";
}
}
$box = new Secret();
echo $box->hint() . "\n";
echo $box->code . "\n";
your turn
Your turn. Lock up the thermostat.
Make $degrees private in the first blank, then make the getter hand back its value. Run it and the heating should be two degrees warmer.
fix it
This game cheats around its own rules. Fix it.
- The error points at line 14:
Cannot access private property. Which line reaches inside the object? $leftis private, so only the class may change it. The class already offers a public method that does exactly this.- Replace line 14 with
$game->lose();, then run it.
nailed it
your objects guard their own rules. :D
privatemembers can only be reached from inside their own class.- Change private data only through methods that check the rules.
- A getter is a public method that returns a private value.
new words in your collection
- visibility
- encapsulation
- getter
This lesson isn’t saved. A free account remembers every lesson you finish.