Limit write access to object function parameters

php.internals

Olle Härstedt

3 years ago
Heyo internalitos, I was thinking of having the possibility to use `readonly` (or any other keyword) to make a function argument behave as if it was a readonly object. class Point { public int $x; public int $y; } function doThing(readonly Point $p) { $p->x = 10; // Not allowed } In C# it's called in/out/ref types: https://www.pluralsight.com/guides/csharp-in-out-ref-parameters The main use-case is to not give away more access than you have to, and being able to state your intent in the function signature. Another alternative would be to allow properties in interfaces, and then define a readonly-like interface: interface ReadonlyPoint { public readonly int $x; public readonly int $y; } function doThing(ReadonlyPoint $p) { $p->x = 10; // Not allowed } No idea about practical feasability. Since arrays are value types, they're not really relevant for this suggestion. Same goes for string, int, etc. Regards Olle

Lokrain

3 years ago
Hey there, Looking at how to achieve “readonly input object” now a few things come in my mind: * Write a readonly class in first place, assuming it’s not a class from a package you cannot or don’t want to update * Clone the object * Use a new immutable DTO for data transfer * Use stateless “services” (DI-ed) * Use static code analysers * Have conversations in your team Having this in mind, such feature looks more or less as syntax sugar with not much value. Nevertheless, I like it :) Hope to see other comments. Regards, Dimitar On Sat, 6 May 2023 at 13:55, Olle Härstedt <olleharstedt@gmail.com> wrote:

Olle Härstedt

3 years ago
2023-05-06 12:55 GMT+02:00, Olle Härstedt <olleharstedt@gmail.com>:
> Heyo internalitos, > > I was thinking of having the possibility to use `readonly` (or any > other keyword) to make a function argument behave as if it was a > readonly object. > > class Point > { > public int $x; > public int $y; > } > function doThing(readonly Point $p) > { > $p->x = 10; // Not allowed > } > > In C# it's called in/out/ref types: > https://www.pluralsight.com/guides/csharp-in-out-ref-parameters > > The main use-case is to not give away more access than you have to, > and being able to state your intent in the function signature. > > Another alternative would be to allow properties in interfaces, and > then define a readonly-like interface: > > interface ReadonlyPoint > { > public readonly int $x; > public readonly int $y; > } > function doThing(ReadonlyPoint $p) > { > $p->x = 10; // Not allowed > } > > No idea about practical feasability. > > Since arrays are value types, they're not really relevant for this > suggestion. Same goes for string, int, etc. > > Regards > Olle
Also related is Object.freeze from JS (I was told): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze Olle