On Sun, Oct 29, 2023, at 9:52 PM, Jorg Sowa wrote:
> I really like the idea and I would love to see it in PHP. I'm wondering
> however, what would be the scope of the feature and how complex would be
> designed type system. Examples I saw in this thread could be easily
> replaced with union and intersection types (i.e. numeric as int|float). In
> my opinion, there is a little benefit implementing in this shape making the
> PHP core more complex.
>
> The two use cases of user defined types in PHP which would benefit a lot
> IMO, would be:
> 1. Typed arrays similar to Typescript.
> 2. Semantic types which would increase the security of systems. Example:
> type UserId = int;
>
> function setUserId_1(int $userId){}
>
> function setUserId_2(UserId $userId){}
>
> setUserId_1(5); // OK
> setUserId_2(5); // TypeError
>
> setUserId_1(UserId(5)); // OK
> setUserId_2(UserId(5)); // OK
>
> Kind regards,
> Jorg

Simple unions are the easiest to talk about in quick examples, but the real 
benefit of type aliases is in other cases, some of which they would enable.

Example:

I have a real parameter defined in my attributes library like this:

\ReflectionProperty|\ReflectionMethod|\ReflectionClassConstant $subject

And it appears several times, I believe.  That would definitely be nicer if 
simplified to an alias.

Example:

There's general consensus that callable types would be beneficial: 
callable(RequestInterface, string): string or similar.  But inline, that gets 
long and complicated fast.  Type aliases would allow simplifying that to 

type callable(RequestInterface, string): string as PropertyRetriever

function foo(PropertyRetriever $c) { ... }

Example:

As in the above example, type aliases serve as documentation for callables or 
complex types, explaining what that complex ruleset actually means, 
semantically.

Example: 

If generics or typed arrays ever happen, they'd probably be useful here, too.

Note that using type aliases in a required-fashion is a different matter, and 
potentially not feasible.  Free standing variables are untyped, which means 
setUserId(UserId $id) could not require a UserId, because there's no way to 
define a variable as being a UserId, not an int.  While I can definitely see a 
value in that kind of restriction, in practice I don't think PHP is capable of 
it without vastly larger changes.

--Larry Garfield

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to