1- # PHP RFC: Short and Inner Classes
1+ # PHP RFC: Inner Classes with Short Syntax
22
33* Version: 0.1
44* Date: 2025-02-08
88
99## Introduction
1010
11- This RFC proposes a new short syntax for class definitions in PHP and the ability to embed these classes within other
11+ This RFC proposes a new short syntax for class/enum definitions in PHP and the ability to embed these classes within other
1212classes.
1313
1414## Proposal
@@ -73,13 +73,33 @@ Attributes may also be used with short classes:
7373class Password(#[SensitiveParameter] string $password);
7474```
7575
76+ ### Short enums
77+
78+ Enums are a common pattern in PHP applications and are usually simple data structures that hold a set of constants.
79+ This RFC includes a proposal for short enums:
80+
81+ ``` php
82+ enum Color(Red, Green, Blue);
83+ ```
84+
85+ This is equivalent to the following full enum definition:
86+
87+ ``` php
88+ enum Color {
89+ case Red;
90+ case Green;
91+ case Blue;
92+ }
93+ ```
94+
7695### Inner Classes
7796
7897Inner classes are classes that are defined within another class.
7998
8099``` php
81100class Foo {
82101 class Bar(public string $message);
102+ enum Baz(One, Two, Three);
83103
84104 private class Baz {
85105 public function __construct(public string $message) {}
@@ -160,7 +180,7 @@ class Foo {
160180
161181#### Names
162182
163- Inner classes may not have any name that conflicts with a constant or static method of the same name.
183+ Inner classes may not have any name that conflicts with a constant or static property of the same name.
164184
165185``` php
166186class Foo {
@@ -171,25 +191,33 @@ class Foo {
171191}
172192
173193class Foo {
174- static function Bar() {}
194+ static $ Bar = 'bar';
175195 class Bar(public string $message);
176196
177197 // Fatal error: Uncaught Error: Cannot redeclare Foo::Bar
178198}
179199```
180200
181201These rules are to prevent developer confusion because these instantiations all look similar,
182- but without this rule, they would all work :
202+ however, the following all result in the same inner class being instantiated :
183203
184204``` php
185- new (Foo::Bar); // create a new class from the name stored in Foo::Bar
186- new (Foo::Bar()); // create a new instance from the name returned by Foo::Bar()
187- new Foo::Bar(); // create a new instance of the class Foo::Bar
205+ new (Foo::Bar);
206+ new (Foo::$ Bar);
207+ new Foo::Bar();
188208```
189209
190210## Backward Incompatible Changes
191211
192- What breaks, and what is the justification for it?
212+ Creating a new instance from an existing static member is now allowed:
213+
214+ ``` php
215+ class Foo {
216+ public const Bar = 'bar';
217+ }
218+
219+ new Foo::Bar(); // previously this is a syntax error, but now results in creating a new "bar" object.
220+ ```
193221
194222## Proposed PHP Version(s)
195223
0 commit comments