Re: [RFC] Data Classes

From: Date: Sat, 23 Nov 2024 22:22:40 +0000
Subject: Re: [RFC] Data Classes
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On 23/11/2024 20:27, Rob Landers wrote:
Interesting! I actually found it to be intuitive. Think of it like this: function increment(array $array) {   $array[0]++; } $arr = [0]; increment($arr); echo $arr[0]; // is 0 We don't expect $arr to be any different outside of the function because $arr is a value, not a reference.
My mental model, rightly or wrongly, is that passing to a parameter is a bit like an assignment to a local variable: function increment(array) {    $array = $__args[0];    $array[0]++; } (This is explicitly how subroutine parameters work in Perl; I don't know if that's affected my mental model, or just means Larry Wall pictured it the same way.) You can even assign a new value to it, like any other variable: function whatever(array $array) {    $array = 'not even an array any more'; } But in PHP, $this isn't a parameter, and it's never possible to assign a new value to $this; so it feels completely alien to have a method where $this stops referring to the current object, and becomes a local variable.
I think it would be clearer to prevent direct modification of $this:
Not that I disagree (see the records RFC), but at that point, why not make data classes implicitly readonly?
I'm only suggesting restricting mutation on $this, not on the object itself. $foo->x++ would still work, and have automatic copy-on-write; but $this->x++ would be an error on a data class, just as $this=$bar is an error on all existing objects.
That would still be compatible with Ilija's suggestion, which was to add special "mutating methods":
I actually find this appealing, but it is strange to me to allow this syntax on classes. Is there precedent for that? Or is there a way we can do it using "regular looking PHP"; or are structs the way to go?
The way I see it, it's just a third type of method, to add to the two we already have: - instance methods: $this refers to the current instance - static methods: $this is forbidden - mutating methods: $this refers to the desired result of the mutation In fact, it's a bit like __construct or __clone, where $this refers to the newly created/copied object, before anything else points to it. -- Rowan Tommins [IMSoP]

Thread (17 messages)

« previous php.internals (#126043) next »