# [RFC] [PRE-VOTE] Union types

- Thread: https://externals.io/message/93713
- Original archive: https://news-web.php.net/php.internals/93713
- Started by Bob Weinand on 2016-06-02T11:00:05+00:00
- Messages: 46
- RFC: Union Types (Declined) — https://externals.io/rfc/union_types.md
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/93713.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #93713 — Bob Weinand — 2016-06-02T11:00:05+00:00

URL: https://externals.io/message/93713#93713

Hey all,

I know, it has been quite some time … but it's still well in time for 7.1.

Time to move on and put Union types to vote soon. [In the next 1-2 days]

We have done some changes to the RFC to emphasize the appeal of union types as well as clarified what exactly we will vote on.

If you have more feedback, it's welcome: https://wiki.php.net/rfc/union_types

Thanks,
Bob

---

## #93721 — Andrea Faulds — 2016-06-02T17:11:26+00:00

URL: https://externals.io/message/93713#93721 · In reply to: #93713

Hi Bob,

Bob Weinand wrote:
> Hey all,
>
> I know, it has been quite some time … but it's still well in time for 7.1.
>
> Time to move on and put Union types to vote soon. [In the next 1-2 days]
>
> We have done some changes to the RFC to emphasize the appeal of union types as well as clarified what exactly we will vote on.
>
> If you have more feedback, it's welcome: https://wiki.php.net/rfc/union_types

I do wonder if 1-2 days is really sufficient time, given that before 
now, the only announced RFC had been substantially less complete.

That aside, the behaviour the RFC now specifies for how weak typing 
interacts with union types is frighteningly complicated. I don't see how 
it could be anything other than that, but the new complexity this 
introduces to PHP is enough for me to vote against this RFC, even 
ignoring my other concerns.

Thanks.
-- 
Andrea Faulds
https://ajf.me/

---

## #93722 — Rowan Collins — 2016-06-02T17:33:04+00:00

URL: https://externals.io/message/93713#93722 · In reply to: #93721

> That aside, the behaviour the RFC now specifies for how weak typing
> interacts with union types is frighteningly complicated. I don't see how
> it could be anything other than that, but the new complexity this
> introduces to PHP is enough for me to vote against this RFC, even
> ignoring my other concerns.

That is rather a long-winded set of rules, I agree. I wonder if it's 
possible for the order the union type is defined to be taken into 
account? That way you could specify the rule thus:

* The type is tested against each type in the union in turn.
* If weak typing is active, scalar types will be coerced where this 
would normally be allowed, and passed over where a TypeError would be 
thrown.
* If strict typing is active, scalar types will be treated the same as 
non-scalar types, and must match precisely.


So:

function f(int | float $number) { echo gettype($number); }
f('10'); // int

function g(float | int $number) { echo gettype($number); }
g('10'); // float

function h(int | Foo | string) { echo gettype($number); }
h('10'); // int
h(new Foo); // object
h('hello'); // string

function i(string | int) { echo gettype($number); }
i('10'); // string
i(10); // string

This last example is the only one that might be a bit surprising - the 
"| int" in the type def is actually doing nothing - but there's always 
scope for user error.


In strict mode, things would be a bit different, because no coercion is 
allowed:

declare(strict_types=1);

function f(int | float $number) { echo gettype($number); }
f('10'); // [!] TypeError

function g(float | int $number) { echo gettype($number); }
g('10'); // [!] TypeError

function h(int | Foo | string) { echo gettype($number); }
h('10'); // string
h(new Foo); // object
h('hello'); // string

function i(string | int) { echo gettype($number); }
i('10'); // string
i(10); // int


It may be that the implementation makes this prohibitively difficult, 
but it would certainly be easier to document than the rules currently 
proposed.

Regards,
-- 
Rowan Collins
[IMSoP]

---

## #93724 — Bob Weinand — 2016-06-02T17:37:20+00:00

URL: https://externals.io/message/93713#93724 · In reply to: #93721

> Am 02.06.2016 um 19:11 schrieb Andrea Faulds <ajf@ajf.me>:
> 
> Hi Bob,
> 
> Bob Weinand wrote:
> > […]
> 
> I do wonder if 1-2 days is really sufficient time, given that before now, the only announced RFC had been substantially less complete.
> 
> That aside, the behaviour the RFC now specifies for how weak typing interacts with union types is frighteningly complicated. I don't see how it could be anything other than that, but the new complexity this introduces to PHP is enough for me to vote against this RFC, even ignoring my other concerns.
> 
> Thanks.
> -- 
> Andrea Faulds
> https://ajf.me/


Hey,

I think this is more of a presentation problem.
As you say, there's not much a better way to do that.

It's basically our weak casting rules, just applied to the most lossless type available.
It's out weak casting rules which are so complex; the RFCs combination is not particularly complex.
It needs to cover everything, but it's particularly important for the trivial cases to be handled here. Would be quite WTF if you could not pass a float to something accepting int (as one of its types).

I'd welcome every suggestion to make the rules look less scary, because they actually aren't.

Bob

---

## #93725 — Bob Weinand — 2016-06-02T17:43:07+00:00

URL: https://externals.io/message/93713#93725 · In reply to: #93722

> Am 02.06.2016 um 19:33 schrieb Rowan Collins <rowan.collins@gmail.com>:
> 
> 
> > […]
> 
> That is rather a long-winded set of rules, I agree. I wonder if it's possible for the order the union type is defined to be taken into account? That way you could specify the rule thus:
> 
> * The type is tested against each type in the union in turn.
> * If weak typing is active, scalar types will be coerced where this would normally be allowed, and passed over where a TypeError would be thrown.
> * If strict typing is active, scalar types will be treated the same as non-scalar types, and must match precisely.
> 
> 
> So:
> 
> function f(int | float $number) { echo gettype($number); }
> f('10'); // int
> 
> function g(float | int $number) { echo gettype($number); }
> g('10'); // float
> 
> function h(int | Foo | string) { echo gettype($number); }
> h('10'); // int
> h(new Foo); // object
> h('hello'); // string
> 
> function i(string | int) { echo gettype($number); }
> i('10'); // string
> i(10); // string
> 
> This last example is the only one that might be a bit surprising - the "| int" in the type def is actually doing nothing - but there's always scope for user error.
> 
> 
> In strict mode, things would be a bit different, because no coercion is allowed:
> 
> declare(strict_types=1);
> 
> function f(int | float $number) { echo gettype($number); }
> f('10'); // [!] TypeError
> 
> function g(float | int $number) { echo gettype($number); }
> g('10'); // [!] TypeError
> 
> function h(int | Foo | string) { echo gettype($number); }
> h('10'); // string
> h(new Foo); // object
> h('hello'); // string
> 
> function i(string | int) { echo gettype($number); }
> i('10'); // string
> i(10); // int
> 
> 
> It may be that the implementation makes this prohibitively difficult, but it would certainly be easier to document than the rules currently proposed.
> 
> Regards,
> -- 
> Rowan Collins
> [IMSoP]

We had that exact idea relatively early, but it exposes other problems… order suddenly matters. You cannot just add "a" type and get the expected results.

E.g.
function f(true | string $foo) { ... }

everything except 0, ±0, "0" and "" would now return true. That's totally WTF. Sure, it's more friendly for people who want to read *rules*. But it is very bad for intuitivity.

Also:

> function i(string | int) { echo gettype($number); }
> i('10'); // string
> i(10); // string

This. This is especially bad as it has different behaviors in strict and weak mode then. That's a no-go.

The current way is the only viable one, as far as we discovered.

Bob

---

## #93726 — Fleshgrinder — 2016-06-02T17:52:32+00:00

URL: https://externals.io/message/93713#93726 · In reply to: #93724

> Hey,
> 
> I think this is more of a presentation problem.
> As you say, there's not much a better way to do that.
> 
> It's basically our weak casting rules, just applied to the most lossless type available.
> It's out weak casting rules which are so complex; the RFCs combination is not particularly complex.
> It needs to cover everything, but it's particularly important for the trivial cases to be handled here. Would be quite WTF if you could not pass a float to something accepting int (as one of its types).
> 
> I'd welcome every suggestion to make the rules look less scary, because they actually aren't.
> 
> Bob
> 

Don't you think this matrix would be a better presentation and simpler?

|--------|--------|--------|--------|
| type   |   #1   |   #2   |   #3   |
|--------|--------|--------|--------|
| bool   | string | int    |        |
| int    | string | float  | bool   |
| float  | string | int    | bool   |
| object | string |        |        |
| string | float  | int    | bool   |
|--------|--------|--------|--------|

Everything else is a TypeError.

Note that I try string first all the time. Simply because it makes no
difference for PHP afterwards, e.g.:

  function f(string|int $a) {
    if ($a == 1) echo 'foo';
  }

  f(true); // true ~> '1' ~> 1 = foo

Even if the change I applied is not intelligent and is not a good idea
(haven't thought about it deeply), the presentation as a table should
help a lot.

-- 
Richard "Fleshgrinder" Fussenegger

---

## #93728 — Bob Weinand — 2016-06-02T18:45:35+00:00

URL: https://externals.io/message/93713#93728 · In reply to: #93726

> Am 02.06.2016 um 19:52 schrieb Fleshgrinder <php@fleshgrinder.com>:
> 
> 
> > […]
> 
> Don't you think this matrix would be a better presentation and simpler?
> 
> |--------|--------|--------|--------|
> | type   |   #1   |   #2   |   #3   |
> |--------|--------|--------|--------|
> | bool   | string | int    |        |
> | int    | string | float  | bool   |
> | float  | string | int    | bool   |
> | object | string |        |        |
> | string | float  | int    | bool   |
> |--------|--------|--------|--------|
> 
> Everything else is a TypeError.

Done that, does it look better now? :-)

> Note that I try string first all the time. Simply because it makes no
> difference for PHP afterwards, e.g.:
> 
>  function f(string|int $a) {
>    if ($a == 1) echo 'foo';
>  }
> 
>  f(true); // true ~> '1' ~> 1 = foo
> 
> Even if the change I applied is not intelligent and is not a good idea
> (haven't thought about it deeply), the presentation as a table should
> help a lot.

There is one reason, it must not be inconsistent with strict types. Switching from strict_types=1 to strict_types=0 shall always work without semantics changes (as long as you don't catch TypeErrors).

> -- 
> Richard "Fleshgrinder" Fussenegger


Thanks,
Bob

---

## #93729 — Fleshgrinder — 2016-06-02T18:53:46+00:00

URL: https://externals.io/message/93713#93729 · In reply to: #93728

> Done that, does it look better now? :-)
> 

Absolutely in my opinion, looks much simpler now. :)

> only if actually numeric, the result of $str + 0

Shouldn't we use is_numeric_string() here?

-- 
Richard "Fleshgrinder" Fussenegger

---

## #93730 — Bob Weinand — 2016-06-02T19:13:23+00:00

URL: https://externals.io/message/93713#93730 · In reply to: #93729

> Am 02.06.2016 um 20:53 schrieb Fleshgrinder <php@fleshgrinder.com>:
> 
> 
> > […]
> 
> Absolutely in my opinion, looks much simpler now. :)
> 
> > […]
> 
> Shouldn't we use is_numeric_string() here?

That's the internal function responsible for the conversion.

Bob

> -- 
> Richard "Fleshgrinder" Fussenegger

---

## #93731 — Bob Weinand — 2016-06-02T19:49:40+00:00

URL: https://externals.io/message/93713#93731

> Am 02.06.2016 um 21:43 schrieb Fleshgrinder <php@fleshgrinder.com>:
> 
> 
> > […]
> 
>  php -r 'var_dump("foo" + 0);'
>  int(0)
> 
> This is what I am referring too. Shouldn't this crap result in an error?
> 
>  is_numeric($x) || throw TypeError('no no');
> 
> -- 
> Richard "Fleshgrinder" Fussenegger
> 


Oh, well… Better now?

Bob

---

## #93732 — Rowan Collins — 2016-06-02T20:25:01+00:00

URL: https://externals.io/message/93713#93732 · In reply to: #93725

> We had that exact idea relatively early, but it exposes other problems… order suddenly matters. You cannot just add "a" type and get the expected results.
>
> E.g.
> function f(true | string $foo) { ... }
>
> everything except 0, ±0, "0" and "" would now return true. That's totally WTF. Sure, it's more friendly for people who want to read*rules*. But it is very bad for intuitivity.

I'm not so sure about that - the RFC already mentions the mnemonic that 
"|" means "or", and anyone reading PHP code should be familiar with 
short-cutting boolean operators, so this feels kind of natural to me: 
"$foo must be true OR a string". Thus "I would prefer it to be true, but 
if not, will accept a string".



> Also:
>
> > […]
> This. This is especially bad as it has different behaviors in strict and weak mode then. That's a no-go.

Again, the logic is "I would prefer a string if you can, but an int if 
not"; if weak mode tries its best to match that specification, it will 
always land on a string coercion.

It's more of a problem the other way around, though, because I'd 
forgotten that weak mode is allowed to perform lossy casts:

function f ( int | string $number ) { echo $number; }
f('1a');

In weak mode, this would echo "1", because the int cast succeeds, 
lossily. That's a little odd, I admit.


The rules are much clearer in table form, by the way, thumbs up for 
that. :) Although it would be nice to point to some documentation of 
where these rules were lifted from, given the claim that "they are not 
the invention of this proposal".

Looking at them, I see there is one extra rule which doesn't seem to be 
consistent with normal weak typing, but is trying very hard to be 
lossless, and that's "float -> int (if lossless)" as a separate priority 
from "float -> int".

Current loose typing performs no such check:

function f(int $x) { echo gettype($x), ':', $x; }
f(4.5); // integer:4

But the proposal is that this will prefer a string a cast:

function f(int | string $x) { echo gettype($x), ':', $x; }
f(4.5); // string:4.5

If you get rid of this extra rule, the order of checks actually becomes 
a simple priority order, regardless of source type: [exact match], int, 
float, string, boolean.


If the aim is to be lossless, then perhaps the order could be tweaked to 
make lossy casts always lower priority: string, float, int, boolean? 
That's technically lossy when passing int(9007199254740993) to "float | 
int" because it's above the safe threshold of 2^53, but the current 
implementation is already lossy when passing it to "float | string":

function f(float | string $x) { var_export($x); }
f(9007199254740993); // 9007199254740992.0

Regards,

-- 
Rowan Collins
[IMSoP]

---

## #93733 — Bob Weinand — 2016-06-02T20:56:28+00:00

URL: https://externals.io/message/93713#93733 · In reply to: #93732

> Am 02.06.2016 um 22:25 schrieb Rowan Collins <rowan.collins@gmail.com>:
> 
> 
> > […]
> 
> I'm not so sure about that - the RFC already mentions the mnemonic that "|" means "or", and anyone reading PHP code should be familiar with short-cutting boolean operators, so this feels kind of natural to me: "$foo must be true OR a string". Thus "I would prefer it to be true, but if not, will accept a string".

This is a bitwise or (as in constant flags), where all modes are allowed. It's not a boolean or, whose mnemonic is "||" (not "|").

> > […]
> 
> Again, the logic is "I would prefer a string if you can, but an int if not"; if weak mode tries its best to match that specification, it will always land on a string coercion.

And again, in strict mode, this would result in an integer - but not in weak mode. (because strict types mandates no cast). This is a no-go, no matter what.

> It's more of a problem the other way around, though, because I'd forgotten that weak mode is allowed to perform lossy casts:
> 
> function f ( int | string $number ) { echo $number; }
> f('1a');
> 
> In weak mode, this would echo "1", because the int cast succeeds, lossily. That's a little odd, I admit.
> 
> 
> The rules are much clearer in table form, by the way, thumbs up for that. :) Although it would be nice to point to some documentation of where these rules were lifted from, given the claim that "they are not the invention of this proposal".

E.g. object->string is possible right now and is preserved (but object->int etc. aren't).
Or a non-numeric string cannot be passed to neither int nor float; thus not possible to pass them to int|float. 

> Looking at them, I see there is one extra rule which doesn't seem to be consistent with normal weak typing, but is trying very hard to be lossless, and that's "float -> int (if lossless)" as a separate priority from "float -> int".

I'm not strictly opposed here. If more people agree here I may change that.

> Current loose typing performs no such check:
> 
> function f(int $x) { echo gettype($x), ':', $x; }
> f(4.5); // integer:4
> 
> But the proposal is that this will prefer a string a cast:
> 
> function f(int | string $x) { echo gettype($x), ':', $x; }
> f(4.5); // string:4.5
> 
> If you get rid of this extra rule, the order of checks actually becomes a simple priority order, regardless of source type: [exact match], int, float, string, boolean.
> 
> 
> If the aim is to be lossless, then perhaps the order could be tweaked to make lossy casts always lower priority: string, float, int, boolean? That's technically lossy when passing int(9007199254740993) to "float | int" because it's above the safe threshold of 2^53, but the current implementation is already lossy when passing it to "float | string":
> 
> function f(float | string $x) { var_export($x); }
> f(9007199254740993); // 9007199254740992.0

Yes, but this same behavior we have with strict types and we shall adhere to that.

Bob

> 
> Regards,
> 
> -- 
> Rowan Collins
> [IMSoP]

---

## #93735 — Sara Golemon — 2016-06-03T01:41:07+00:00

URL: https://externals.io/message/93713#93735 · In reply to: #93713

> I know, it has been quite some time … but it's still well in time for 7.1.
>
> Time to move on and put Union types to vote soon. [In the next 1-2 days]
>
> We have done some changes to the RFC to emphasize the appeal of union types as well as clarified what exactly we will vote on.
>
> If you have more feedback, it's welcome: https://wiki.php.net/rfc/union_types
>
Would it be COMPLETELY antisocial at this point to ask for a secondary
vote on this RFC for adding the "num" type which is an alias for (int
| float) ?

-Sara

---

## #93736 — Bob Weinand — 2016-06-03T02:23:03+00:00

URL: https://externals.io/message/93713#93736 · In reply to: #93735

> Am 03.06.2016 um 03:41 schrieb Sara Golemon <pollita@php.net>:
> 
> > […]
> Would it be COMPLETELY antisocial at this point to ask for a secondary
> vote on this RFC for adding the "num" type which is an alias for (int
> | float) ?
> 
> -Sara

Not anti-social, but I won't add it...

The main concern is that it is an extra BC break (num is not too rare for class/namespace names I'd argue).
Additionally it warrants extra discussion. Num, Numeric? Which one?
Also proper elaboration why we should add it or not would have to be done...

I think this should be an own RFC thus.

Bob

---

## #93740 — Thomas Bley — 2016-06-03T10:16:59+00:00

URL: https://externals.io/message/93713#93740 · In reply to: #93733

why not try all types weakly from left to right in weak mode?
Rule: if type check would give a fatal error for a type, try next type.

E.g.
function i(int | string $var) { echo gettype($var) . ' ' . $var; }
i('10'); // int 10
i('10a'); // int 10
i('foo'); // string foo
i(10.0); // int 10
i(10); // int 10

Regards
Thomas

Bob Weinand wrote on 02.06.2016 22:56:

> 
> > […]
> 
> This is a bitwise or (as in constant flags), where all modes are allowed. It's
> not a boolean or, whose mnemonic is "||" (not "|").
> 
> > […]
> 
> And again, in strict mode, this would result in an integer - but not in weak
> mode. (because strict types mandates no cast). This is a no-go, no matter what.
> 
> > […]
> 
> E.g. object->string is possible right now and is preserved (but object->int
> etc. aren't).
> Or a non-numeric string cannot be passed to neither int nor float; thus not
> possible to pass them to int|float. 
> 
> > […]
> 
> I'm not strictly opposed here. If more people agree here I may change that.
> 
> > […]
> 
> Yes, but this same behavior we have with strict types and we shall adhere to
> that.
> 
> Bob
> 
> > […]

---

## #93741 — Rowan Collins — 2016-06-03T10:28:04+00:00

URL: https://externals.io/message/93713#93741 · In reply to: #93740

> why not try all types weakly from left to right in weak mode?
> Rule: if type check would give a fatal error for a type, try next type.

This is what I suggested, but Bob is insistent that weak mode should 
always select the same type as strict mode where there is a valid strict 
match, which I guess makes sense.

A strict left-to-right check violates that:

function i(string | int $x) { echo gettype($x); }
i(10); // string in weak mode, int in strict mode

function j(int | string $x) { echo gettype($x); }
j('10'); // int in weak mode, string in strict mode


The main complication that I haven't quite got my head round yet is the 
fact that an int->float coercion is allowed in strict mode. So to be 
consistent, weak mode needs to privilege that cast:

function k(string | float $x) { echo gettype($x); }
k(10); // float

But in other cases it doesn't seem sensible to privilege float over string:

function l(string | float $x) { echo gettype($x); }
l("1.5a"); // I would expect string, but float would succeed if attempted

Regards,
-- 
Rowan Collins
[IMSoP]

---

## #93742 — Bob Weinand — 2016-06-03T11:59:31+00:00

URL: https://externals.io/message/93713#93742 · In reply to: #93741

> Am 3.6.2016 um 12:28 schrieb Rowan Collins <rowan.collins@gmail.com>:
> 
> 
> > […]
> 
> This is what I suggested, but Bob is insistent that weak mode should always select the same type as strict mode where there is a valid strict match, which I guess makes sense.
> 
> A strict left-to-right check violates that:
> 
> function i(string | int $x) { echo gettype($x); }
> i(10); // string in weak mode, int in strict mode
> 
> function j(int | string $x) { echo gettype($x); }
> j('10'); // int in weak mode, string in strict mode
> 
> 
> The main complication that I haven't quite got my head round yet is the fact that an int->float coercion is allowed in strict mode. So to be consistent, weak mode needs to privilege that cast:
> 
> function k(string | float $x) { echo gettype($x); }
> k(10); // float
> 
> But in other cases it doesn't seem sensible to privilege float over string:
> 
> function l(string | float $x) { echo gettype($x); }
> l("1.5a"); // I would expect string, but float would succeed if attempted

Exact matches *ALWAYS* match without coercion.

Emphasis from the RFC:
Primarily, this issue is *avoided if a parameter type exactly matches the input type* or if PHP is in strict type mode. 

> Regards,
> -- 
> Rowan Collins
> [IMSoP]



Bob

---

## #93743 — Rowan Collins — 2016-06-03T12:18:49+00:00

URL: https://externals.io/message/93713#93743 · In reply to: #93742

> > […]
>
> Exact matches *ALWAYS* match without coercion.

Gah, I keep making that mistake in my examples. I did say I was 
struggling to get my head around things! ;)

I'm still missing an explanation of exactly where you derived the 
current proposed rules from, though. The RFC just states "these rules 
are not an invention of this proposal", but goes on to say "applies PHP 
casting rules in a sane way", which implies some decisions were involved 
in drawing up these rules.

I think you may be right that the rules are as simple as they can be, 
and I don't want to waste too much of your time, but a basic summary of 
the reasoning used would be much appreciated.

Regards,
-- 
Rowan Collins
[IMSoP]

---

## #93744 — Bob Weinand — 2016-06-03T12:30:52+00:00

URL: https://externals.io/message/93713#93744 · In reply to: #93743

> Am 3.6.2016 um 14:18 schrieb Rowan Collins <rowan.collins@gmail.com>:
> 
> 
> > […]
> 
> Gah, I keep making that mistake in my examples. I did say I was struggling to get my head around things! ;)
> 
> I'm still missing an explanation of exactly where you derived the current proposed rules from, though. The RFC just states "these rules are not an invention of this proposal", but goes on to say "applies PHP casting rules in a sane way", which implies some decisions were involved in drawing up these rules.
> 
> I think you may be right that the rules are as simple as they can be, and I don't want to waste too much of your time, but a basic summary of the reasoning used would be much appreciated.
> 
> Regards,
> -- 
> Rowan Collins
> [IMSoP]

The *weak casting* rules (i.e. what gets converted how and what can be converted to the other type) are not an invention of the proposal.

The proposal however defines the specific order.

I’ve added a reasoning why not left-to-right now. As this seemed to be asked multiple times.

Also, the specific reasoning why I propose that specific order the rules are in:
> Otherwise PHP's casting rules are applied in an order to be as lossless as possible.

That’s really the only motivation behind that.

Bob

---

## #93745 — Theodore Brown — 2016-06-03T13:40:40+00:00

URL: https://externals.io/message/93713#93745 · In reply to: #93713

> Hey all,
> 
> I know, it has been quite some time … but it's still well in time for 7.1.
> 
> Time to move on and put Union types to vote soon. [In the next 1-2 days]
> 
> We have done some changes to the RFC to emphasize the appeal of
> union types as well as clarified what exactly we will vote on.
> 
> If you have more feedback, it's welcome: https://wiki.php.net/rfc/union_types
> 
> Thanks,
> Bob

Thank you (and Levi) for this RFC! I can't vote, but I'd like to
weigh in with my userland perspective.

Just last week I was working with several functions that accept
array|Traversable and array|string parameters. Union types would
make it easier to document these functions, as well as eliminate the
boilerplate code currently required to validate their parameters.

I am also in favor of the proposal to replace ?QuestionMarkNullables
with union|null. Having a single way to declare nullable types will
keep the reflection API simpler, make things easier for static
analysis tools, and prevent developers from having to wonder which
syntax they should use for a given function. This would be a big win
for language consistency, and this is probably our only chance to
make the change without breaking BC.

Theodore Brown

---

## #93749 — Thomas Bley — 2016-06-03T14:24:21+00:00

URL: https://externals.io/message/93713#93749

maybe easier to get a majority from voters if defining union types only in strict mode for 7.1?

Regards
Thomas

Rowan Collins wrote on 03.06.2016 15:40:

> 
> > […]
> 
> 
> Cheers, that's more or less what I thought.
> 
> I've yet to come up with a scheme that can be summarised any more simply 
> than that table, but FWIW below is how I've been trying to think about it...
> 
> 
> 
> 
> Strict mode rules are easy; try, in order:
> 0. Match without casting
> 1. Cast int -> float
> 
> Weak mode rules must start with the same rules strict mode would, to 
> avoid confusion.
> 
> After that, there are various casts available, and there's not a clear 
> precedent for the order that I can think of.
> 
> There are two somewhat contradictory aims:
> - use "narrower" types where possible, e.g. for string("") passed to 
> "int | bool" we probably prefer bool(false) over int(0)
> - use lossless casts where possible, e.g. for float(1.5) passed to "int 
> | string" we probably prefer string("1.5") over int(1)
> 
> The following casts are always lossless:
> 
> - anything -> string (with possible exception of float precision limits)
> - boolean -> anything (1 bit of information is easy to retain :P)
> 
> The following may be lossless in some common cases:
> 
> - string -> int (ctype_digit)
> - string -> float (roughly, is_numeric)
> - float -> int (whole numbers)
> - int -> float (where magnitude < 2^53, but this is pre-empted as high 
> priority by the strict rules)
> 
> The following are pretty much always lossy:
> 
> - anything -> boolean
> 
> 
> 
> 
> I'm not quite sure what to conclude from all that, but thought I'd write 
> it down for the record.
> 
> Cheers,
> -- 
> Rowan Collins
> [IMSoP]

---

## #93750 — Rowan Collins — 2016-06-03T14:32:58+00:00

URL: https://externals.io/message/93713#93750 · In reply to: #93749

> maybe easier to get a majority from voters if defining union types only in strict mode for 7.1?

No go, I'm afraid.

Strict types are opt-in at the point of calling the function, but union 
types are a feature of the declaration. If I write "function foo(int | 
string $a) {}", it is not up to me whether it's executed in strict mode 
or not.

We'd have to throw an error of "function %s cannot be called without 
strict types enabled", and that goes against the entire premise of 
strict types as implemented.

Regards,
-- 
Rowan Collins
[IMSoP]

---

## #93751 — Thomas Bley — 2016-06-03T14:58:57+00:00

URL: https://externals.io/message/93713#93751 · In reply to: #93750

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.

Regards
Thomas

Rowan Collins wrote on 03.06.2016 16:32:

> 
> > […]
> 
> No go, I'm afraid.
> 
> Strict types are opt-in at the point of calling the function, but union 
> types are a feature of the declaration. If I write "function foo(int | 
> string $a) {}", it is not up to me whether it's executed in strict mode 
> or not.
> 
> We'd have to throw an error of "function %s cannot be called without 
> strict types enabled", and that goes against the entire premise of 
> strict types as implemented.
> 
> Regards,
> -- 
> Rowan Collins
> [IMSoP]

---

## #93752 — Andrea Faulds — 2016-06-03T15:13:42+00:00

URL: https://externals.io/message/93713#93752 · In reply to: #93724

Hi,

Bob Weinand wrote:
> I think this is more of a presentation problem.
> As you say, there's not much a better way to do that.

Well, that's why I question if we should do it at all, if there's no way 
to do it without this complexity.

> It's basically our weak casting rules, just applied to the most lossless type available.

Right, I think I can see the logic to that. But I don't think it works 
out so well in practice.

Consider the hypothetical example `int|string`. Under your rules, if I 
pass a float to that parameter, it becomes a string.

That makes sense if the function just wants a number, in integer or 
string format, for that parameter.

But what if the function wants either a number (in integer format) or a 
string, and does different things depending on which of these it gets? 
Now the proposed weak typing rules are broken.

A real-world example of this is array indices. Given array keys can be 
either integers or strings, then if we wanted to take an array key as a 
parameter, surely we'd use the type declaration `int|string`, right?

Well, it turns out that in PHP, $a[1.5] is not equivalent to $a["1.5"], 
it's equivalent to $a[1]. Yet, if I pass 1.5 to an `int|string` typed 
parameter, I'd get "1.5". So, we'd end up with an inconsistency:


    <?php
    function fetchValueForKeyInArray(array $array, int|string $key) {
        return $array[$key];
    }
    $arr = ["1.5" => "wrong", 1 => "right"];
    var_dump($arr[1.5]); // string(5) "right"
    var_dump(fetchValueForKeyInArray($arr, $key)); // string(5) "wrong"
    ?>

Trying to do the most "lossless" conversion works for some use-cases, 
but it doesn't work for others, and it doesn't necessarily match 
existing behaviour in other parts of PHP.

This is a wider concern for me, in that union types have two different 
use cases: where you want to accept any type of some ad-hoc super-type 
(int|float as an ad-hoc "number", array|\Traversable as an ad-hoc "thing 
that can be foreach()'d), but there is also the use case of where you 
want to accept two completely unrelated types (int|string for two kinds 
of array key, int|array, etc.) and perhaps do different things depending 
on the types given.

This latter use case strikes me as making a function overly complicated 
(make a separate function instead), and it interacts poorly with weak 
typing (if PHP decides to give you a different type, you get a 
completely different code path!), yet the addition of union types 
encourages writing such functions! (At least, for people who want to use 
type declarations throughout their code.)

Moreover, I think whatever weak typing precedence rules we choose, they 
can only work reasonably for one or the other of these use-cases, not 
both. I think that `int|string` is a succint example of that: whichever 
ruleset we choose, it will do the wrong thing for some usecase, we're 
just deciding which one to privilege.

> It's out weak casting rules which are so complex; the RFCs combination is not particularly complex.

The RFC uses simple rules, but the resulting behaviour is complex.

PHP's weak typing rules are complicated enough as they are, and cause 
enough problem, without the addition of yet more rules, this time for 
how weak typing should work within union types.

I don't think 2 days is enough time to discuss this before voting on it.

Thanks.

-- 
Andrea Faulds
https://ajf.me/

---

## #93753 — Jordi Boggiano — 2016-06-03T15:16:19+00:00

URL: https://externals.io/message/93713#93753 · In reply to: #93751

> 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

-- 
Jordi Boggiano
@seldaek - http://seld.be

---

Next page: https://externals.io/message/93713.md?page=2
