0
0
PHPprogramming~10 mins

Readonly classes in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a readonly class in PHP.

PHP
<?php
[1] class User {
    public string $name;
}
Drag options to blanks, or click blank then click option'
Areadonly
Bfinal
Cabstract
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'final' instead of 'readonly' which prevents inheritance but not property changes.
Using 'static' which is unrelated to readonly properties.
2fill in blank
medium

Complete the code to declare a readonly property in a normal class.

PHP
<?php
class Product {
    public [1] string $sku;
}
Drag options to blanks, or click blank then click option'
Areadonly
Bstatic
Cprivate
Dfinal
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'static' which means the property belongs to the class, not instance.
Using 'final' which is for methods or classes, not properties.
3fill in blank
hard

Fix the error in the readonly class constructor to properly assign the readonly property.

PHP
<?php
readonly class Order {
    public function __construct([1] string $id) {
    }
}
Drag options to blanks, or click blank then click option'
Areadonly
Bprivate
Cpublic
Dfinal
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'readonly' in constructor parameters which is invalid syntax.
Omitting visibility keyword causing property not to be assigned.
4fill in blank
hard

Fill the blank to create a readonly class with a readonly property using constructor property promotion.

PHP
<?php
[1] class Customer {
    public function __construct(public string $email) {}
}
Drag options to blanks, or click blank then click option'
Afinal
Breadonly
Cstatic
Dabstract
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'final' or 'static' instead of 'readonly' for the class.
Thinking you need readonly before the property type (it's invalid in readonly classes).
5fill in blank
hard

Fill the blank to create a readonly class with two readonly properties and a method returning a property.

PHP
<?php
[1] class Invoice {
    public function __construct(public int $number, public float $amount) {}

    public function getAmount(): float {
        return $this->amount;
    }
}
Drag options to blanks, or click blank then click option'
Astatic
Bfinal
Cabstract
Dreadonly
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'final' instead of 'readonly' for the class.
Believing you need readonly keywords before each property type in the constructor.