0
0
PHPprogramming~5 mins

Readonly properties in PHP

Choose your learning style9 modes available
Introduction

Readonly properties let you create values that can only be set once and never changed. This helps keep your data safe and predictable.

When you want to store a value that should not change after it is first set, like a user ID.
When you want to make sure some settings or configuration values stay the same throughout the program.
When you want to prevent accidental changes to important data in your objects.
When you want to clearly show which properties are meant to be fixed after creation.
Syntax
PHP
class ClassName {
    public readonly Type $propertyName;

    public function __construct(Type $value) {
        $this->propertyName = $value;
    }
}

The readonly keyword is placed before the property type and name.

You can only assign a value to a readonly property once, usually in the constructor.

Examples
This example shows a readonly property $id that can only be set when creating a User.
PHP
<?php
class User {
    public readonly int $id;

    public function __construct(int $id) {
        $this->id = $id;
    }
}
Readonly property $appName holds the application name and cannot be changed later.
PHP
<?php
class Config {
    public readonly string $appName;

    public function __construct(string $appName) {
        $this->appName = $appName;
    }
}
Sample Program

This program creates a Product with readonly properties name and price. It prints the product details. Trying to change price after creation will cause an error.

PHP
<?php
class Product {
    public readonly string $name;
    public readonly float $price;

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

$product = new Product("Book", 12.99);
echo "Product: {$product->name}\n";
echo 'Price: $' . $product->price . "\n";

// Trying to change readonly property will cause error
// $product->price = 15.99; // Uncommenting this line will cause an error
OutputSuccess
Important Notes

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

Trying to change a readonly property after it is set will cause a fatal error.

Readonly properties help make your code safer and easier to understand.

Summary

Readonly properties store values that cannot be changed after being set.

They are useful for fixed data like IDs or configuration.

Assign them once, usually in the constructor, and then they stay constant.