0
0
PHPprogramming~5 mins

Readonly properties in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a readonly property in PHP?
A readonly property is a class property that can only be assigned once, typically during object construction, and cannot be changed afterward.
Click to reveal answer
beginner
How do you declare a readonly property in PHP?
You declare a readonly property by adding the readonly keyword before the property type and name inside a class.
Click to reveal answer
beginner
Can you assign a value to a readonly property outside the constructor in PHP?
No, once a readonly property is assigned a value (usually in the constructor), it cannot be changed later anywhere else in the code.
Click to reveal answer
intermediate
What happens if you try to modify a readonly property after it has been set?
PHP will throw an error because readonly properties are immutable after their initial assignment.
Click to reveal answer
beginner
Why use readonly properties in PHP classes?
Readonly properties help protect data by preventing accidental changes, making objects more predictable and safer to use.
Click to reveal answer
How do you declare a readonly property in PHP?
AUse the keyword <code>readonly</code> before the property name
BUse the keyword <code>const</code> before the property name
CUse the keyword <code>final</code> before the property name
DUse the keyword <code>static</code> before the property name
When can you assign a value to a readonly property?
AOnly after the object is destroyed
BMultiple times anywhere in the class
COnly once, typically in the constructor
DOnly inside static methods
What happens if you try to change a readonly property after it is set?
APHP throws an error
BThe property value changes silently
CThe property resets to null
DThe program ignores the change
Which PHP version introduced readonly properties?
APHP 8.0
BPHP 8.1
CPHP 7.4
DPHP 7.0
Why are readonly properties useful?
AThey make properties private
BThey make properties static
CThey allow properties to be changed anytime
DThey prevent accidental changes to important data
Explain what readonly properties are and how they work in PHP.
Think about properties that you set once and then keep safe.
You got /4 concepts.
    Describe a situation where using readonly properties would be helpful in a PHP program.
    Consider data that should never change after creation.
    You got /4 concepts.