Re: Limit write access to object function parameters
| From: | Lokrain | Date: | Sat, 06 May 2023 16:45:20 +0000 |
| Subject: | Re: Limit write access to object function parameters | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-120205@lists.php.net to get a copy of this message | ||
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:
> 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
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>