On Fri, Sep 8, 2023, 9:15 AM Lanre Waju <la...@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.

Reply via email to