Php 8.1 New Features — Readonly Properties

With new version of PHP we have a new feature named Readonly properties. Readonly properties are init and set value just once and we can not change its value. This protects unwanted value changes from anywhere in codebase. Before php 8.1 we do this with creating private property and a getter method in class to get its value. With readonly property we don’t need to do this. We just use a readonly keyword in class definition or in construct method. Every readonly property can set once. If you try to change you will get error.

Example before PHP 8.1 :

After Php 8.1 using readonly keyword

Another way of using readonly property is Constructor Property Promotion method. With this method we pass and define properties in constructor method. Let’s see in some code.

Defining in constructor is 2nd way of defining readonly property. This declaration is same with below.

Property Initialization

Readonly properties can be initialized anywhere in class. All above examples init within constructor method. But we can init in any method in our class. This is a nice addition of PHP and we can init but we can’t change the readonly property.

Let’s go deeper… We can not init any of readonly property out of class. This is another protection of avoiding changes.

When you try this you will get error again..

Also we can not set a default value in class definition. When we define a readonly property , you can not set a default value.

Readonly Enforcement

PHP actively refuses to modify a readonly property. This includes directly setting a value, incrementing it, references, and array operations. You can init once and you can not modify , change it’s value from anywhere in your code base.

Unset Readonly

Yes, we can not modify value of readonly property but can we unset that?

The answer is basicly No.. You can not unset or delete a readonly property. This is another protection of readonly property . Think this way you created and defined a property and you do not want that anyone else delete or modify that property. The readonly keyword added in language for this purpose in very short explanation.

Hope it was a good read.. See you on next article about PHP 8.1 features



Senior Php Developer | Javascript | Python | Ruby

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store