Complete the code to declare a readonly class in PHP.
<?php [1] class User { public string $name; }
In PHP 8.2+, the readonly keyword declares a class whose properties cannot be changed after initialization.
Complete the code to declare a readonly property in a normal class.
<?php class Product { public [1] string $sku; }
The readonly keyword before a property means it can only be assigned once, typically in the constructor.
Fix the error in the readonly class constructor to properly assign the readonly property.
<?php readonly class Order { public function __construct([1] string $id) { } }
The constructor parameter should be declared with visibility like public to allow property promotion and assignment.
Fill the blank to create a readonly class with a readonly property using constructor property promotion.
<?php [1] class Customer { public function __construct(public string $email) {} }
readonly before the property type (it's invalid in readonly classes).Declare the class readonly. Promoted properties are implicitly readonly in readonly classes.
Fill the blank to create a readonly class with two readonly properties and a method returning a property.
<?php [1] class Invoice { public function __construct(public int $number, public float $amount) {} public function getAmount(): float { return $this->amount; } }
readonly keywords before each property type in the constructor.Declaring the class readonly ensures all properties, including the two promoted ones, are readonly and immutable after creation.