Back to questions
JuniorTheoryCommon
What happens when you run this program?
<?php
class Ticket
{
public function __construct(public readonly int $id) {}
}
$t = new Ticket(7);
echo $t->id, "\n";
$t->id = 8;
echo $t->id, "\n";7, then an Error: cannot modify readonly property
- Expecting
8, as ifreadonlywere a note PHP never checks: the property takes its value once, and a second write throws anErrorthat stops the script. - Expecting the second write to be skipped without a word: PHP never ignores a forbidden write, it throws an
Errorat that line.
- How would you get a ticket with id
8without breakingreadonly? - Why may a
readonlyproperty not have a default value?