Re: [RFC] Type Aliases
| From: | Larry Garfield | Date: | Wed, 03 Dec 2025 15:51:19 +0000 |
| Subject: | Re: [RFC] Type Aliases | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-129524@lists.php.net to get a copy of this message | ||
On Tue, Dec 2, 2025, at 4:23 PM, Rob Landers wrote:
> Hello Internals,
>
> I’d like to request your comments on type aliases (not to be confused
> with typedefs) at https://wiki.php.net/rfc/typed-aliases
>
> TL;DR (it’s actually rather short):
>
> Following the same syntax as other use'ing statements, you can alias a type:
>
> use type int|float as Number;
>
> function sum(Number $a, Number $b): Number { return $a + $b; }
>
> You can also include types, with some restrictions:
>
> include types 'math-types.php';
>
> function sum(Number $a, Number $b): Number { return $a + $b; }
>
> These are compile-time replacements that serve to make code more
> readable and reduce repetition with no runtime overhead. Type aliases
> follow the same scoping rules as other use imports.
>
> — Rob
Thanks, Rob! This does seem like a good low-hanging fruit piece to attack. Most importantly, I
don't see anything here that would preclude more formal TypeDef structures in the future.
A few other notes:
- Should
mixed be allowed as in an alias definition? Since mixed matches
anything, it would render the entire alias redundant as it's then equivalent to
mixed.
- What if any conflict resolution is there if you include two different type files that declare the
same alias?
- Because it's all compile time, I assume two aliases with the same source but different names
become compatible?
Eg:
use type string|Stringable as Stringy;
use type string|Stringable as Stringish;
Those are mutually compatible in practice, yes?
- Are aliases case sensitive? You're using Capitalized names in the RFC, but I don't know
if that means anything... (Please state in the RFC.)
- The "include type" syntax implies that it would not be possible to pre-load aliases via
Composer autoload or opcache preloading. (Well, maybe the latter.) That feels like an unnecessary
limitation, and is my main issue with the current design. Some way to have project-wide or
package-wide definitions would be very helpful, without needing a manual include statement in every
file.
- Does it matter where the include type statement goes? Must it be at the top under
the use statements, or could it be anywhere?
- Not allowing use statements in type include files: This feels like a very unfortunate
limitation. Is there any way to obviate that? It's all compile time, as you said...
Overall, I am tentatively in favor.
--Larry Garfield