Bird
Raised Fist0
PHPprogramming~20 mins

Readonly classes in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Readonly Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of readonly class property assignment
What will be the output of this PHP code using a readonly class?
PHP
<?php
readonly class User {
    public string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}

$user = new User("Alice");
echo $user->name;
$user->name = "Bob";
echo $user->name;
AAliceBob
BFatal error: Cannot declare readonly class User
CAliceAlice
D
Alice
Fatal error: Cannot modify readonly property User::$name
Attempts:
2 left
💡 Hint
Readonly classes allow properties to be assigned only once, typically in the constructor.
🧠 Conceptual
intermediate
1:30remaining
Behavior of readonly classes with mutable properties
Which statement about readonly classes in PHP is true?
AReadonly classes prevent reassignment of properties but do not prevent mutation of objects assigned to properties.
BReadonly classes only allow properties to be assigned in the constructor and nowhere else, including nested objects.
CReadonly classes allow modification of properties if they are objects, but not scalar values.
DReadonly classes prevent modification of all properties, including objects referenced by properties.
Attempts:
2 left
💡 Hint
Think about how readonly affects references to objects stored in properties.
🔧 Debug
advanced
2:00remaining
Identify the error in readonly class property initialization
What error will this PHP code produce?
PHP
<?php
readonly class Product {
    public string $name = "Default";
    public function __construct() {
        $this->name = "Gadget";
    }
}

$product = new Product();
echo $product->name;
AGadget
BFatal error: Cannot initialize readonly property Product::$name twice
CDefault
DParse error: Unexpected token '='
Attempts:
2 left
💡 Hint
Readonly properties can only be assigned once, either at declaration or in constructor, not both.
📝 Syntax
advanced
1:30remaining
Valid syntax for declaring a readonly class
Which of the following PHP code snippets correctly declares a readonly class with a readonly property?
A
class Car readonly {
    public readonly string $model;
    public function __construct(string $model) {
        $this-&gt;model = $model;
    }
}
B
class readonly Car {
    public string $model readonly;
    public function __construct(string $model) {
        $this-&gt;model = $model;
    }
}
C
readonly class Car {
    public string $model;
    public function __construct(string $model) {
        $this-&gt;model = $model;
    }
}
D
readonly class Car {
    public readonly string $model;
    public function __construct(string $model) {
        $this-&gt;model = $model;
    }
}
Attempts:
2 left
💡 Hint
The readonly keyword must appear before class and property declarations correctly.
🚀 Application
expert
2:00remaining
Count properties in a readonly class after instantiation
Given this readonly class, how many properties does the object have after creation?
PHP
<?php
readonly class Book {
    public string $title;
    public string $author;
    public function __construct(string $title, string $author) {
        $this->title = $title;
        $this->author = $author;
    }
}

$book = new Book("1984", "Orwell");
$props = get_object_vars($book);
echo count($props);
A2
B1
C0
DFatal error: Cannot access properties of readonly class
Attempts:
2 left
💡 Hint
Readonly properties are still accessible and countable like normal properties.

Practice

(1/5)
1. What does a readonly class in PHP ensure about its properties?
easy
A. Properties are static and shared between all instances.
B. Properties can be changed anytime after creation.
C. All properties cannot be changed after the object is created.
D. Properties are private and cannot be accessed outside the class.

Solution

  1. Step 1: Understand the meaning of readonly class

    A readonly class means all its properties are readonly by default, so they cannot be changed after the object is created.
  2. Step 2: Compare options with this definition

    Only the option stating "All properties cannot be changed after the object is created." correctly states that properties cannot be changed after creation.
  3. Final Answer:

    All properties cannot be changed after the object is created. -> Option C
  4. Quick Check:

    Readonly class = immutable properties [OK]
Hint: Readonly means no property changes after creation [OK]
Common Mistakes:
  • Thinking readonly means private or static
  • Assuming properties can be changed anytime
  • Confusing readonly with access modifiers
2. Which of the following is the correct syntax to declare a readonly class in PHP?
easy
A. readonly class User { public readonly string $name; }
B. class readonly User {}
C. class User readonly {}
D. readonly class User {}

Solution

  1. Step 1: Recall PHP readonly class syntax

    In PHP, the keyword readonly comes before class to declare a readonly class.
  2. Step 2: Check each option

    readonly class User {} correctly uses readonly class User {}. class readonly User {} reverses the order, class User readonly {} places readonly incorrectly, and readonly class User { public readonly string $name; } is invalid syntax.
  3. Final Answer:

    readonly class User {} -> Option D
  4. Quick Check:

    Keyword readonly before class [OK]
Hint: Put readonly before class keyword [OK]
Common Mistakes:
  • Placing readonly after class name
  • Using readonly as a property only
  • Mixing readonly with access modifiers
3. What will be the output of this PHP code?
readonly class Point {
    public int $x;
    public int $y;
    public function __construct(int $x, int $y) {
        $this->x = $x;
        $this->y = $y;
    }
}

$p = new Point(5, 10);
echo $p->x . ', ' . $p->y;
medium
A. 5, 10
B. Error: Cannot modify readonly property
C. 0, 0
D. 5 10

Solution

  1. Step 1: Understand readonly class property initialization

    Readonly properties can be set inside the constructor. Here, $x and $y are set to 5 and 10 respectively.
  2. Step 2: Check output of echo statement

    The echo prints 5, 10 as expected because the properties were initialized correctly and not modified later.
  3. Final Answer:

    5, 10 -> Option A
  4. Quick Check:

    Readonly properties set in constructor output values [OK]
Hint: Readonly properties can be set in constructor only [OK]
Common Mistakes:
  • Thinking readonly properties cannot be set at all
  • Expecting error on property access
  • Confusing output format with space instead of comma
4. Identify the error in this PHP code using a readonly class:
readonly class User {
    public string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}

$user = new User('Alice');
$user->name = 'Bob';
medium
A. Cannot assign to readonly property after construction
B. Missing readonly keyword before property declaration
C. Constructor must be static in readonly class
D. No error, code runs fine

Solution

  1. Step 1: Understand readonly property behavior

    In a readonly class, properties can only be assigned once during construction. Changing them later causes an error.
  2. Step 2: Analyze the code

    The code tries to change $user->name after construction, which is not allowed and causes an error.
  3. Final Answer:

    Cannot assign to readonly property after construction -> Option A
  4. Quick Check:

    Readonly properties are immutable after construction [OK]
Hint: Readonly properties cannot be changed after constructor [OK]
Common Mistakes:
  • Thinking readonly properties can be changed anytime
  • Confusing readonly class with readonly property keyword
  • Ignoring error on property reassignment
5. Given this readonly class, which code snippet correctly creates an immutable user and tries to update the name without error?
readonly class User {
    public string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}

Choose the correct approach:
hard
A. $user = new User('Alice'); $user->name = 'Bob';
B. $user = new User('Alice'); $newUser = new User('Bob');
C. $user = new User('Alice'); $user->name = strtoupper($user->name);
D. $user = new User('Alice'); unset($user->name);

Solution

  1. Step 1: Understand immutability of readonly classes

    Readonly class properties cannot be changed after construction, so to 'change' data, create a new object with new values.
  2. Step 2: Evaluate each option

    $user = new User('Alice'); $user->name = 'Bob'; tries to change property directly - error. $user = new User('Alice'); $user->name = strtoupper($user->name); tries to modify property - error. $user = new User('Alice'); $newUser = new User('Bob'); creates a new User object with new name - correct. $user = new User('Alice'); unset($user->name); tries to unset property - invalid.
  3. Final Answer:

    Create a new User object with updated name -> Option B
  4. Quick Check:

    Immutable means create new object for changes [OK]
Hint: Change readonly data by creating new object [OK]
Common Mistakes:
  • Trying to modify readonly property directly
  • Using unset on readonly properties
  • Assuming readonly means properties can be changed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard