Re: RFC Proposal: Readonly Structs in PHP
| From: | Lanre Waju | Date: | Fri, 08 Sep 2023 15:09:39 +0000 |
| Subject: | Re: RFC Proposal: Readonly Structs in PHP | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-121016@lists.php.net to get a copy of this message | ||
I really like the idea of making structs opaque in that sense, definitely going to put it to vote in the RFC. I agree with the decision to exclude methods from structs, as they are intended to be pure data types and If methods are required, classes can be used instead. I guess based on the response from this list i might not need to put it up to a vote.
On 2023-09-08 8:58 a.m., Matthew Weier O'Phinney wrote:
On Fri, Sep 8, 2023, 9:15 AM Lanre Waju <lanre@online-presence.ca> wrote:Allowing Methods in Structs: Initially, I suggested that readonly structs have no methods besides the constructor. However, upon further consideration, I believe it may be beneficial to allow methods in structs. Even PHP enums allow methods, and considering this, I am open to discussing and potentially having a vote on allowing methods within structs as part of the RFC discussion.At that point, a struct would be no different from a readonly class with public properties, meaning we'd have two ways to accomplish the same thing. Considering that a readonly class can already implement interfaces such as JsonSerializable, Iterator, and ArrayAccess, they already solve the bulk of the issues that have been raised in this thread. The main thing of interest that I could see from your proposal was the ability to nest a struct in another struct or a class definition, as that could provide some interesting type safety without the need to declare new classes. This could be even more interesting if it allowed _any_ struct that fulfilled the same definitions:class Post { public function __construct( public readonly struct $author { string $name; UriInterface $uri; UriInterface $avatarUri; }, public readonly string $title, public readonly string $content, public readonly DateTimeInterface $publicationDate, ) { }// ... }struct User { string $name; UriInterface $uri; UriInterface $avatarUri; string $email; }$post = new Post(new User(...), ...);The idea here is that User fulfills the $author struct definition in the Post class; it just has _additional_ properties. If the proposal would allow that, this could be pretty powerful. I would personally stay away from solving the conversion to and from arrays and allowing methods. If users need those, they can either use de/serialization libraries or readonly classes, respectively. Not including them in the initial proposal keeps it more targeted, and demonstrates a language feature that does not currently exist.