Readonly properties are a new feature in PHP 8.1 that allows you to declare class properties that can only be initialized once and cannot be modified later. Readonly properties can help you write more secure and consistent code by preventing accidental or unwanted changes to the property values. In this tutorial, you will learn how to use readonly properties in PHP 8.1 with practical examples.



What Are Readonly Properties?

A readonly property is a class property that can only be assigned a value once, either in the property declaration or in the class constructor. A readonly property is declared with the readonly keyword before the type declaration. For example, you can create a class with a readonly property to represent a user:

class User {
    public readonly int $id;
    public function __construct(int $id) {
        $this->id = $id;
    }
}

You can use the class name and the arrow operator (->) to access the readonly property value. For example, you can create an instance of the class and print the property value:

$user = new User(123);
echo $user->id; // Outputs 123

However, after initializing it, you cannot assign a new value to the readonly property. Doing so will throw an Error exception. For example, the following code will cause an error:

$user = new User(123);
$user->id = 456; // Error: Cannot modify readonly property User::$id

Note that readonly properties are truly immutable, even from within class methods.

Adding Methods and Constants to Readonly Properties

Readonly properties can also have methods and constants, just like regular properties. You can define methods inside the readonly property definition using the public keyword. Methods can be either instance methods or static methods. Instance methods can use $this to refer to the current readonly property value, while static methods can use self to refer to the readonly property class:

class Temperature {
    public readonly int $celsius;
    public function __construct(int $celsius) {
        $this->celsius = $celsius;
    }

    public function fahrenheit(): float {
        return ($this->value * 9/5) + 32;
    }

    public static function fromFahrenheit(float $fahrenheit): self {
        return new self(($fahrenheit - 32) * 5/9);
    }
}

You can call instance methods on readonly property values and static methods on readonly property names:

$temp = new Temperature(25);
echo $temp->celsius; // 25
echo $temp->celsius->fahrenheit(); // 77

$temp2 = Temperature::fromFahrenheit(68);
echo $temp2->celsius; // 20

You can also define constants inside the readonly property definition using the const keyword. Constants can be used to store additional information related to the readonly property:

class Currency {
    public readonly string $code;
    public function __construct(string $code) {
        $this->code = $code;
    }

    const SYMBOLS = [
        self::USD => '$',
        self::EUR => '€',
        self::GBP => '£',
        // ...
    ];

    const USD = 'USD';
    const EUR = 'EUR';
    const GBP = 'GBP';
}

You can access constants using the readonly property name and the double colon operator (::):

$currency = new Currency(Currency::USD);
echo $currency->code; // USD
echo Currency::SYMBOLS[$currency->code]; // $

When to Use Readonly Properties?

Readonly properties are a great way to represent a fixed set of related values with a semantic meaning. Readonly properties can improve the security and consistency of your code by preventing accidental or unwanted changes to the property values. Readonly properties can also help you avoid errors and bugs by ensuring the property values are always valid and up-to-date. Some examples of when you can use readonly properties are:

  • IDs, codes, names, etc.
  • Colors, temperatures, currencies, etc.
  • Statuses, states, modes, etc.
  • Options, flags, settings, etc.

Conclusion

In this tutorial, you learned how to use readonly properties in PHP 8.1 with practical examples. You learned how to add methods and constants to readonly properties, and when to use readonly properties in your code.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram