Re: [RFC][Concept] Data classes (a.k.a. structs)

From: Date: Tue, 02 Apr 2024 22:35:34 +0000
Subject: Re: [RFC][Concept] Data classes (a.k.a. structs)
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-122900@lists.php.net to get a copy of this message
Hi Niels On Tue, Apr 2, 2024 at 8:16 PM Niels Dossche <dossche.niels@gmail.com> wrote: > > On 02/04/2024 02:17, Ilija Tovilo wrote: > > Hi everyone! > > > > I'd like to introduce an idea I've played around with for a couple of > > weeks: Data classes, sometimes called structs in other languages (e.g. > > Swift and C#). > > As already hinted in the thread, I also think inheritance may be dangerous in a first version. > I want to add to that: if you extend a data-class with a non-data-class, the data-class > behaviour gets lost, which is logical in a sense but also surprised me in a way. Yes, that's definitely not intended. I haven't implemented any inheritance checks yet. But if inheritance is allowed, then it should be restricted to classes of the same kind (by-ref or by-val). > Also, FWIW, I'm not sure about the name "data" class, perhaps "value" > class or something alike is what people may be more familiar with wrt semantics, although dataclass > is also a known term. I'm happy with value class, struct, record, data class, what have you. I'll accept whatever the majority prefers. > I do have a question about iterator behaviour. Consider this code: > ``` > data class Test { > public $a = 1; > public $b = 2; > } > > $test = new Test; > foreach ($test as $k => &$v) { > if ($k === "b") > $test->a = $test; > var_dump($k); > } > ``` > > This will reset the iterator of the object on separation, so we will get an infinite loop. > Is this intended? > If so, is it because the right hand side is the original object while the left hand side gets > the clone? > Is this consistent with how arrays separate? That's a good question. I have not really thought about iterators yet. Modification of an array iterated by-reference does not restart the iterator. Actually, by-reference capturing of the value also captures the array by-reference, which is not completely intuitive. My initial gut feeling is to handle data classes the same, i.e. capture them by-reference when iterating the value by reference, so that iteration is not restarted. Ilija

« previous php.internals (#122900) next »