When should one use read-only properties / classes?
Readonly classes in PHP 8.2
PHP 7.4 typed properties are a bit of a waste without readonly declarations
Or am I just being paranoid about library users doing stupid things with public properties?
On the contrary, which is why public properties are only advisable when making basic "struct-like" objects to carry data around without expectations of encapsulation.
I agree readonly and other enhancements (like unions, etc.) would significantly improve the utility of prop types (and types in general). But think about what we got as a step in the right direction, for now.
Remember when typed return types were introduced in PHP 7.0 we didn't have nullable typehints. Huge omission. But we got it eventually. And 7.0 was the first step in getting what we have today.
More on reddit.comReadonly properties RFC by Nikita
Videos
I discovered this feature a few weeks ago and end up using it a lot in my DTOs (most times they end up being read-only classes).
Right now, the only other use case I have for it is for class properties injected via dependency injection, which I believe should probably never be changed to anything else than what it was first instantiated as.
I'm not sure if the DI properties is a good excuse for using read-only, or if there are other use cases I might have missed, which is why I'm asking how you guys use it :)