Bird
Raised Fist0
PHPprogramming~20 mins

Readonly properties in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Readonly Properties Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of readonly property assignment

What will be the output of this PHP code using readonly properties?

PHP
<?php
class User {
    public readonly string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}
$user = new User("Alice");
echo $user->name;
?>
AAlice
BFatal error: Cannot modify readonly property User::$name
Cnull
DParse error: syntax error, unexpected 'readonly'
Attempts:
2 left
💡 Hint

Readonly properties can be assigned once, usually in the constructor.

❓ Predict Output
intermediate
2:00remaining
Error on modifying readonly property after construction

What happens when you try to modify a readonly property after the object is created?

PHP
<?php
class Point {
    public readonly int $x;
    public function __construct(int $x) {
        $this->x = $x;
    }
}
$p = new Point(5);
$p->x = 10;
echo $p->x;
?>
A10
BFatal error: Cannot modify readonly property Point::$x
C5
DParse error: syntax error
Attempts:
2 left
💡 Hint

Readonly properties cannot be changed after initial assignment.

🧠 Conceptual
advanced
2:00remaining
Readonly property initialization timing

When can a readonly property be assigned a value in PHP?

AOnly once, but anywhere in the class methods
BMultiple times anywhere in the class methods
COnly once, and only inside the constructor or at property declaration
DOnly at the moment of object destruction
Attempts:
2 left
💡 Hint

Think about when readonly properties get their value safely.

🔧 Debug
advanced
2:00remaining
Identify the error with readonly property usage

What error will this code produce?

PHP
<?php
class Config {
    public readonly array $settings = [];
    public function addSetting(string $key, string $value): void {
        $this->settings[$key] = $value;
    }
}
$config = new Config();
$config->addSetting('theme', 'dark');
print_r($config->settings);
?>
AEmpty array output
BArray ( [theme] => dark )
CParse error: syntax error, unexpected '['
DFatal error: Cannot modify readonly property Config::$settings
Attempts:
2 left
💡 Hint

Readonly means the property cannot be changed after initialization, including its contents.

🚀 Application
expert
2:00remaining
Using readonly properties with nested objects

Consider this code. What will be the output?

PHP
<?php
class Address {
    public readonly string $city;
    public function __construct(string $city) {
        $this->city = $city;
    }
}
class Person {
    public readonly Address $address;
    public function __construct(Address $address) {
        $this->address = $address;
    }
}
$addr = new Address('Paris');
$person = new Person($addr);
$person->address->city = 'London';
echo $person->address->city;
?>
AFatal error: Cannot modify readonly property Address::$city
BParis
CLondon
DFatal error: Cannot modify readonly property Person::$address
Attempts:
2 left
💡 Hint

Readonly applies to the property itself, but what about the object it points to?

Practice

(1/5)
1. What is the main purpose of readonly properties in PHP?
easy
A. To store values that cannot be changed after being set
B. To allow properties to be changed anytime
C. To make properties private
D. To automatically generate getter methods

Solution

  1. Step 1: Understand readonly property behavior

    Readonly properties in PHP are designed to hold values that can only be assigned once and cannot be modified later.
  2. Step 2: Compare options with this behavior

    To store values that cannot be changed after being set correctly describes this behavior, while others describe unrelated features.
  3. Final Answer:

    To store values that cannot be changed after being set -> Option A
  4. Quick Check:

    Readonly means unchangeable after set = A [OK]
Hint: Readonly means value set once and then fixed [OK]
Common Mistakes:
  • Thinking readonly allows changes anytime
  • Confusing readonly with private visibility
  • Assuming readonly auto-generates methods
2. Which of the following is the correct syntax to declare a readonly property in a PHP class?
easy
A. readonly public int $id;
B. public readonly int $id;
C. public int readonly $id;
D. int public readonly $id;

Solution

  1. Step 1: Recall PHP property declaration order

    In PHP, visibility (public/private/protected) comes first, then readonly keyword, then type and variable name.
  2. Step 2: Match syntax with options

    public readonly int $id; matches the correct order: public readonly int $id;. Others have incorrect order.
  3. Final Answer:

    public readonly int $id; -> Option B
  4. Quick Check:

    Visibility then readonly then type = B [OK]
Hint: Visibility keyword comes before readonly in declaration [OK]
Common Mistakes:
  • Placing readonly before visibility
  • Putting readonly after type
  • Mixing order of keywords
3. What will be the output of the following PHP code?
class User {
    public readonly string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}
$user = new User('Alice');
echo $user->name;
$user->name = 'Bob';
echo $user->name;
medium
A. Alice followed by a fatal error
B. BobBob
C. AliceBob
D. Syntax error

Solution

  1. Step 1: Understand readonly property assignment

    The readonly property $name is assigned once in the constructor to 'Alice'. This is allowed.
  2. Step 2: Analyze second assignment

    Trying to assign $user->name = 'Bob'; after construction causes a fatal error because readonly properties cannot be changed after initial assignment.
  3. Final Answer:

    Alice followed by a fatal error -> Option A
  4. Quick Check:

    Readonly blocks changes after set = C [OK]
Hint: Readonly allows one assignment only, later changes cause error [OK]
Common Mistakes:
  • Assuming readonly properties can be changed anytime
  • Expecting no error on second assignment
  • Confusing syntax error with runtime error
4. Identify the error in the following PHP code using readonly properties:
class Config {
    public readonly string $version;
    public function __construct() {
        $this->version = '1.0';
        $this->version = '2.0';
    }
}
medium
A. No error, code is correct
B. Missing visibility keyword for property
C. Readonly keyword used incorrectly with string type
D. Assigning readonly property twice in constructor

Solution

  1. Step 1: Check property assignments in constructor

    The readonly property $version is assigned twice: first '1.0', then '2.0'.
  2. Step 2: Understand readonly assignment rules

    Readonly properties can only be assigned once, even inside the constructor. Assigning twice causes an error.
  3. Final Answer:

    Assigning readonly property twice in constructor -> Option D
  4. Quick Check:

    Readonly assigned once only = A [OK]
Hint: Assign readonly property only once, even in constructor [OK]
Common Mistakes:
  • Assigning readonly property multiple times
  • Ignoring visibility keyword importance
  • Thinking readonly disallows string type
5. Given this PHP class with readonly properties, which code correctly creates an immutable user with an ID and name?
class User {
    public readonly int $id;
    public readonly string $name;
    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

Choose the correct usage:
hard
A. $user = new User(1, 'John'); $user->name = 'Jane';
B. $user = new User(1); $user->name = 'John';
C. $user = new User(1, 'John'); // no changes after construction
D. $user = new User(); $user->id = 1; $user->name = 'John';

Solution

  1. Step 1: Check constructor usage

    The constructor requires two parameters: int $id and string $name. $user = new User(1, 'John'); // no changes after construction correctly calls the constructor with both.
  2. Step 2: Verify immutability

    Readonly properties cannot be changed after construction. $user = new User(1, 'John'); // no changes after construction respects this by not modifying properties after creation.
  3. Final Answer:

    $user = new User(1, 'John'); // no changes after construction -> Option C
  4. Quick Check:

    Construct with all params, no changes after = D [OK]
Hint: Call constructor fully, then do not modify readonly properties [OK]
Common Mistakes:
  • Trying to assign readonly properties after construction
  • Calling constructor with missing arguments
  • Assuming properties can be set without constructor
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