Home > OS >  What is the benefit of readonly in PHP 8.1?
What is the benefit of readonly in PHP 8.1?

Time:12-07

readonly is now available in PHP 8.1, I just wonder what is the use of it? Is that to help the editor to know that this property is just readonly or to help the client to know that or there is another benefit?

CodePudding user response:

readonly properties allow you to create immutable objects, or at the very least immutable properties.

That way you can be sure that a value won't be changed by accident after being initialized, throughout the object's life.

It's a very similar concept to constants (set via const or define), albeit with two important differences: constants live in a global space, and constants need to be defined on "compilation" time, whereas readonly properties will be set during runtime, usually during on object instantiation (so multiple instances will be able to hold different values, as opposed with constants, which are global).

CodePudding user response:

I think it is the same to what exist in c#, so take a look on this answer

https://stackoverflow.com/a/277023/4003872

  • Related