php · level 3 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A property is written once, then locked for good.
Some values should never change once set: a ticket's seat, a payment's amount, a user's id. Mark a property readonly and PHP allows exactly one write, from inside the class. Any later change throws an Error, even from the class itself.
An object whose properties are all readonly is . Need a different value? Build a new object. A with method does this neatly: it returns a fresh copy with one thing changed and leaves the original alone, so nothing can surprise you later.
<?php
class Money {
public function __construct(
public readonly int $pence,
public readonly string $currency,
) {}
public function withPence(int $pence): self {
return new self($pence, $this->currency);
}
}
$price = new Money(250, "GBP");
$sale = $price->withPence(199);
echo "$price->pence $price->currency, now $sale->pence $sale->currency\n"; Readonly properties need a type, so write readonly int, never readonly on its own.
guess first
Somebody wants a better seat. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
class Seat {
public function __construct(public readonly string $number) {}
}
$seat = new Seat("B12");
echo "Your seat: $seat->number\n";
$seat->number = "A1";
echo "New seat: $seat->number\n";
your turn
Your turn. Order a pizza with a twist.
Copy the size across in the first blank, then type any topping you fancy. The plain pizza should stay exactly as it was.
fix it
Adding points breaks the score. Make it immutable.
- The error is
Cannot modify readonly property Score::$pointson line 6. Is changing the object allowed at all? - An immutable object never changes. Instead of updating itself,
plusshould hand back a brand new score. - Delete line 6 and change
return $this;toreturn new self($this->points + $extra);, then run it.
nailed it
your values cannot change by accident. :D
- A
readonlyproperty is set once, and any later change throws. - Immutable objects never change, so build a new one instead.
- A
withmethod returns a changed copy and keeps the original.
new words in your collection
- readonly
- immutable
This lesson isn’t saved. A free account remembers every lesson you finish.