0
0
PHPprogramming~10 mins

Readonly properties 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 property in a PHP class.

PHP
<?php
class User {
    public [1] string $name;
}
Drag options to blanks, or click blank then click option'
Aconst
Bprivate
Cstatic
Dreadonly
Attempts:
3 left
💡 Hint
Common Mistakes
Using const instead of readonly for properties.
Using static which is unrelated to immutability.
2fill in blank
medium

Complete the constructor to assign a value to the readonly property.

PHP
<?php
class User {
    public readonly string $name;

    public function __construct([1]) {
        $this->name = $name;
    }
}
Drag options to blanks, or click blank then click option'
Astring $name
Bint $name
Cbool $name
Darray $name
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different type like int or bool which causes type errors.
Not declaring the parameter type at all.
3fill in blank
hard

Fix the error by completing the code to prevent modifying a readonly property after construction.

PHP
<?php
class User {
    public readonly string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function changeName([1]) {
        $this->name = $newName;
    }
}
Drag options to blanks, or click blank then click option'
Aarray $newName
Bint $newName
Cstring $newName
Dbool $newName
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign a new value to a readonly property after construction.
Using a wrong parameter type.
4fill in blank
hard

Fill both blanks to create a readonly property and assign it in the constructor.

PHP
<?php
class Product {
    public [1] int $id;

    public function __construct([2]) {
        $this->id = $id;
    }
}
Drag options to blanks, or click blank then click option'
Areadonly
Bstring $id
Cint $id
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Using string type for the constructor parameter when property is int.
Forgetting the readonly keyword.
5fill in blank
hard

Fill all three blanks to declare a readonly property, assign it in the constructor, and prevent modification.

PHP
<?php
class Order {
    public [1] float $amount;

    public function __construct([2]) {
        $this->amount = $amount;
    }

    public function updateAmount([3]) {
        $this->amount = $newAmount;
    }
}
Drag options to blanks, or click blank then click option'
Areadonly
Bfloat $amount
Cfloat $newAmount
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to modify a readonly property after construction.
Using mismatched types for parameters.