Hi,
On 26.10.23 08:37, Oladoyinbo Vincent wrote:
Greetings to you all,
I will like to submit an RFC on introducing type alias to php.
Even though Generics won't or never be introduced to PHP, personally i will
like php to add the type alias feature.
Type aliases provide a mechanism to create more descriptive and readable
type hints in PHP code. This enhancement will improve code readability and
maintainability and also to promote type reusability.
Motivation:
The motivation behind introducing type aliases is to:
1. Enhance code readability by allowing developers to use meaningful type
hint names.
2. Improve code maintainability by reducing the likelihood of type hint
updates throughout the codebase.
3. Encourage the adoption of best practices for type hinting.
Proposal:
Syntax:
Type aliases will be declared using the `type` or `typealias` keyword,
followed by the alias name, an equal sign (`=`), and the type it is aliased
to.
Sample:
```
type MyType = string;
// or
typealias MyType = string;
// Advance
type MyType = string|null;
// or
type MyType = [string, null];
```
Usage:
Type aliases can be used in parameter and return type hints as follows:
```
function greetings(MyType $message): string {
// Implementation
}
greetings(1); // TypeError
```
Since this is just a basic feature, Type aliases Inheritance (compound
type) may not be added, since we are not digging deeper into generics :).
References:
https://docs.python.org/3/glossary.html#term-type-alias
https://doc.rust-lang.org/beta/reference/items/type-aliases.html
https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#type-aliases
So, What do you think?
I would love to see type aliases added to PHP but I think it would be
very less useful if it's scoped per file only.
Like `type UserId = string;` in it's self already improves readability
but only if reusable by different files and because of that a big
question about autoloading/performance comes in here as well.
About the syntax: I think this should be consistent with how we declare
types right now ...
`type UserId: string;` instead of `type UserId = string;`
Another question is how the type annotations will behave if the aliased
type is hinted:
type UserId: string;
function test(UserId $userId): string {
return $userId;
}
test("its-me");
Also, would it be possible to handle types as specialized classes
including namespaces, helper functions and usable with reflection?
type UserId: string;
type OtherId: UserId;
UserId::base // "string"
OtherId::base // "string"
UserId::nullable // false
UserId::isValid(mixed $var): bool
$refl = ReflectionClass(UserId::class);
$refl = ReflectionType::from(UserId::class);
...
Best,
Marc
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php