Re: [RFC] [PRE-VOTE] Union types
| From: | Bob Weinand | Date: | Fri, 03 Jun 2016 21:31:43 +0000 |
| Subject: | Re: [RFC] [PRE-VOTE] Union types | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-93759@lists.php.net to get a copy of this message | ||
> Am 3.6.2016 um 18:49 schrieb Larry Garfield <larry@garfieldtech.com>:
>
> On 06/03/2016 10:16 AM, Jordi Boggiano wrote:
>> On 03/06/2016 15:58, Thomas Bley wrote:
>>> To me type declarations help to make my code easier and more consistent.
>>> Having multiple scalar types for a single function parameter is against this goal since
>>> I need extra logic to handle this.
>>>
>>> e.g. function foo(string | int | bool $bar) {} makes no sense in weak mode since string
>>> can already handle int, bool, float, etc.
>>>
>>> having different behavior between
>>> foo("42"); function foo(string $b) {echo gettype($b);} // string
>>> and
>>> foo("42"); function foo(string | int $b) {echo gettype($b);} // integer
>>> also makes no sense to me.
>>>
>>> Things like string|array are useful (e.g. str_replace) since we can cast the string
>>> easily to array and calling a string parameter with an array would give a fatal error.
>>
>> That is a useful case, and don't forget also return values, e.g. all the XX|false-kind
>> of return types it's also nice to have.
>>
>> I don't think for function arguments it's massively useful and I doubt it'll
>> get put everywhere, but it's nice to be able to express this when you have to.
>>
>> Cheers
>
> For parameters, I really don't think | is going to be the common use case. (It should
> still be rational, but I don't expect to see it day to day.) InterfaceA & InterfaceB Is
> the more useful use case for parameters. | is, as noted, likely more useful on returns. (even
> though I would discourage their use in most cases for reasons I won't go into here).
>
> --Larry Garfield
It won’t and it should not be *common*. But there are legit uses cases:
https://github.com/amphp/aerys/blob/2a4d626fb1b8b8ac9d91711085c04eaabdec7768/lib/Host.php#L87
<https://github.com/amphp/aerys/blob/2a4d626fb1b8b8ac9d91711085c04eaabdec7768/lib/Host.php#L87>
This concrete example shows that a class may implement multiple concrete interfaces which all get
the same/similar behavior locally. [And somewhere else the code checks for each element in the array
what classes it implements and marks them appropriately.]
Sure, you could have ->addMiddleware($foo)->addRequest($foo) … or just a single
->add($foo). It’s maybe not the most pure API, but the most practical one.
But I agree, I myself would discourage usage of union types in most cases too; but there *are*
legitimate cases which shall be also properly typable. Thus we need it.
Bob