Short class syntax and inner classes

From: Date: Fri, 07 Feb 2025 14:23:48 +0000
Subject: Short class syntax and inner classes
Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
Hey internals,

You may remember my RFC about Records (https://wiki.php.net/rfc/records).. There was something
intentionally left out, and due to life events, I am quite behind schedule on this one. BUT, what I
left out (and the main reason for the short syntax) is the ability to have locally scoped records in
a class definition.

Example using an anonymous record:

$x = new class {
  public record Point(int $x, int $y);

  // from inside the class, there is no special scope
  public function foo(): Point {
    return new Point(1, 1);
  }
}

$point = new $x::Point(1, 2);

Anyway, I think I've settled on an implementation that is acceptable, but I wanted your
feedback before moving forward.

Instead of this being limited to Records -- an entirely new type of type and syntax -- would we
rather have short class declarations (similar to the rules in the Records RFC) and locally scoped
classes?

class Outer {
  // able to be instantiated from anywhere
  public class Inner(int $y);
  // a private/protected class can only be instantiated within methods/classes bound to Outer
  protected readonly class ProtectedInner(int $z);
}

Instantiation is done by static access: new Outer::Inner(1), which is currently a syntax error.
Public nested classes may be used as type hints and return types as well as properties in other
classes.

There are quite a few more things left to investigate before updating the RFC (or drafting a new
one), but I am at a crossroads and I wanted to gather people's feedback first. If this is a big
"NO" (or if someone else has started working on this and I'm just so happening to
accidentally step on their toes, again): I don't want to spend several days/weeks digging into
the details for classes. However, it would probably look something like the above.

Note, this doesn't preclude you from using a longer syntax, if that is your preference.

class Outer {
  public class Inner {
    public function __construct(public int $z) {}
  }
}

Anyway, I'd love to hear any preferences or thoughts -- strong or otherwise. I probably
won't reply, but I will read everything and take it into consideration as I continue down this
road.

Also, if there is already someone working on this ... please speak up so I don't get accused of
stealing ideas again!

— Rob


Thread (4 messages)

« previous php.internals (#126331) next »