On 9 November 2024 08:39:57 GMT, Adam Kecskes <kecskes.a...@outlook.com> wrote:
>I propose adding first-class types to PHP, as this feature could greatly 
>enhance the language, especially given PHP's unique runtime type-checking 
>system. Many libraries currently rely on class strings as function parameters, 
>which could be made significantly safer with native types rather than strings.


Hi Adam, 

I think this is an interesting idea to think about, although I have no idea 
what the implementation might look like.

One of the things I've been thinking about for some time is how to improve 
PHP's type casting functionality, and a key sticking point is a sufficiently 
flexible syntax. Not wanting to get into the casting itself, let's imagine we 
want to add "foo casts", available for all types, including unions, nullable 
types, etc; options seem to be: 

- foo_cast("int|string", $value) - a "stringly typed" function with no new 
syntax; flexible, but ugly and awkward to statically analyse 
- foo_cast($value as int|string) - a new keyword for each type of cast; 
expressive, but a high barrier to adding more casting options
- foo_cast<int|string>($value) - if we add generics, even without type 
inference, that syntax could be used to "specialise" by type
- foo_cast(int|string, $value) - passing the type as a parameter would read 
very nicely

There's a lot of overlap between the last two, but also some differences:

- generics give a clear way of expressing that the function will return the 
given type, or perhaps some manipulation of it, like "function 
foo_cast<T>(mixed $value): T|CastError"
- first-class types, on the other hand, give a clear way for userland to pass 
around type specifications, like "function cast_in_turn(mixed $value, type 
...$types): array { /* loop over $types, calling foo_cast($type, $value) for 
each one */ }"

Would first-class types and generics need to be mutually exclusive, to avoid a 
confusing overlap of functionality? Or could they be made explicitly 
complementary somehow?

I wonder what prior art there is in this area, in both the theory of type 
systems, and the practice of language implementations?

Regards,
Rowan Tommins
[IMSoP]

Reply via email to