Settings

Theme

PHP Type Alias

3 points by oladoyinbov 2 years ago · 4 comments · 1 min read


i was kinda wondering maybe it's worth it to write an RFC on PHP type alias. this will be really useful in the sense of maintenance, re-usability, readability and many more..

``` <?php

type T = bool|int;

type Result = string;

function greeting(T $input): Result { return match() {

      true, 1 => 'hello user :) ',

      false, 2 => 'good-bye user'
  }
}

```

What's your opinion on this?

moritzwarhier 2 years ago

Sounds great. But I supsect PHP had to make big tradeoffs for its checked-at-runtime types that would make this hard.

In contrast to TypeScript or Flow, which can only check the program flow at compile time, PHP will crash and burn if you pass an int into a string function parameter at runtime.

Would you expect the presumed type aliases to be checked at runtime too?

There are already union types in PHP 8, but no aliases.

I think in PHP it is always the best approach to work with classes, whose type you can check at runtime (in contrast to duck-typed languages such as JS, where there is instanceof but that is generally a last resort).

Structural types checked at compile time are a different approach to the one PHP chose I think. Alhough the lines between compilation and execution are blurry in a JIT language of course.

stefanos82 2 years ago

That is something I was looking for to be honest with you, but didn't know how to "look" for it lol.

I had in mind the modern C++ `using` mechanism for creating my own types, but didn't know how to write such logic.

I guess a union would be handy dealing with different alias types, depending on the use case, if you understand what I mean.

On the other hand, `match` is far better to be used if we really get type aliases as you suggest.

stefanos82 2 years ago

How about overloading `as` operator instead and use `alias` in place of `type`?

Something like `alias Numeric as int|float;`

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection