Re: [RFC] Type Aliases
| From: | Rob Landers | Date: | Tue, 02 Dec 2025 22:51:47 +0000 |
| Subject: | Re: [RFC] Type Aliases | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-129520@lists.php.net to get a copy of this message | ||
On Tue, Dec 2, 2025, at 23:41, Oladoyinbo Vincent wrote:
> Can we follow the approach other languages used for their type alias implementation?
>
> ```php
> typedef UserType: string|null;
>
> // or
>
> typedef UserType = UserStatus|AlternativeType|null;
> ```
>
> We could also introduce a way to group multiple type alias in a single file:
>
> ```php
> namespace App;
>
> typedef TypeGroup {
> typedef UserType: string|null;
> typedef CustomType: \MyCustomType|\AnotherType|null;
> }
>
> ```
>
> Then, it can be imported by using:
>
> ```php
>
> // single
> use type UserType;
>
> // group
> use type App\TypeGroup;
>
> ```
>
> This feels more familiar, nice and structured.
>
> *NOTE:* it's just a suggestion from my own view.
>
> On Tue, 2 Dec 2025, 11:24 pm Rob Landers, <rob@bottled.codes> 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
A typedef is a bit different. It’s a real type.
I’m working on combining my Records RFC and the pattern matching RFC (assuming it gets accepted).
Thus you’ll be able to do something like:
typedef UserID: int is > 0;
Which would basically compile into the previous Record:
record UserID(int $value) { $value > 0 }
-ish.
That gets you value semantics and with a bit more work, inherited operators (numbers act like
numbers, arrays act like arrays, strings like strings, etc).
It doesn’t need pattern matching, but it really helps. This is just aliases, which are
complementary but separate.
PS: please remember to bottom post (write your reply under the person you are replying to).
— Rob