# [RFC] Match expression

- Thread: https://externals.io/message/100487
- Original archive: https://news-web.php.net/php.internals/100487
- Started by ilija.tovilo@me.com on 2017-09-09T11:21:03+00:00
- Messages: 23
- 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

---

## #100487 — ilija.tovilo@me.com — 2017-09-09T11:21:03+00:00

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

Hi everybody!

Has this idea been discussed before?

I find myself writing switch statements in PHP quite rarely. This has a few reasons:

1. It doesn’t have a "strict_types” version
2. It is quite verbose (lots of breaks)
3. It is a statement rather than an expression

Often, if / elseif statements turn out to be shorter, safer and easier to read than the switch statement.
What I’d really love is something like a match expression:

```
$r = match ($x) {
    1: ‘Tiny’;
    <= 10: ‘Small’;
    <= 20: ‘Medium’;
    <= 30: ‘Large’;
    range(31, 100): ‘Enormous’; // Equivalent to `in_array($x, range(31, 100), true)`
    instanceof Foo, instanceof Bar: ‘What?’;
    default: ‘Unknown’;
};
```

These are the main differences compared to a traditional `switch` statement:

- The whole `match` is an expression, the result of the executed `case` is implicitly returned
- It allows pattern matching, not just `==` comparison, `===` is the default
- It does no implicit type conversion, thus no unexpected results when mixing strings and numbers
- Each case has an implicit `break`
    - Where you’d previously use two `case`s without a break, you now combine conditions using a comma

One downside, since PHP doesn’t implicitly return the last statement as some languages do there’s no obvious way to do multi-statement cases.

I assume that some people will not be so happy about having to switch-like constructs. IMO the implicit type conversion is the biggest issue here. Maybe we could offer a solution for this one at least.

Just some random thoughts.

Regards

---

## #100488 — Andreas Treichel — 2017-09-09T12:11:04+00:00

URL: https://externals.io/message/100487#100488 · In reply to: #100487

Hi,

Something like:

function match($x) {
     switch(true) {
         case $x === 1:
             return 'Tiny';
         case is_numeric($x) && $x <= 10:
             return 'Small';
         case is_numeric($x) && $x <= 20:
             return 'Medium';
         case is_numeric($x) && $x <= 30:
             return 'Large';
         case is_numeric($x) && ($x >= 31 || $x <= 100):
             return 'Enormous';
         case $x instanceof Foo:
         case $x instanceof Bar:
             return 'What?';
         default:
             return 'Unknown';
     }
}

the problem is you need is_numeric because no type safe version of <= 
and >= exists.

---

## #100489 — Dan Ackroyd — 2017-09-09T12:18:04+00:00

URL: https://externals.io/message/100487#100489 · In reply to: #100488

> Hi everybody!
>
> Has this idea been discussed before?
> ..
> Each case has an implicit `break`

This part has come up before, as the default behaviour of fall through
is a nasty gotcha for when you forget to put break. I can't find the
conversation right now, but the discussion was around a 'select'
keyword. I think the conversation didn't proceed as it seemed like
adding a new keyword just to fix the fall-through behaviour was a bad
tradeoff.

This RFC idea adds more capabilities, so is a better trade-off, and
more likely to be worth doing in my opinion.

> One downside, since PHP doesn’t implicitly return the last statement
> as some languages do there’s no obvious way to do multi-statement cases.

People are still working on and hoping for short-closures. That RFC
and any potential one for this, should attempt to use the same syntax.



> Something like:
>
> *wall_of_hard_to_read_code*

Yeah, that's a pretty good example of why I'd be in favour of this RFC.


cheers
Dan
Ack

---

## #100491 — Thomas Hruska — 2017-09-09T16:41:58+00:00

URL: https://externals.io/message/100487#100491 · In reply to: #100489

> for when you forget to put break.

Applying break statements is the first thing you should do if you intend 
to break.  That way it can't be forgotten.

-- 
Thomas Hruska
CubicleSoft President

I've got great, time saving software that you will find useful.

http://cubiclesoft.com/

And once you find my software useful:

http://cubiclesoft.com/donate/

---

## #100492 — ilija.tovilo@me.com — 2017-09-09T16:47:40+00:00

URL: https://externals.io/message/100487#100492 · In reply to: #100491

> Applying break statements is the first thing you should do if you intend
> to break. That way it can't be forgotten.

You should also immediately free the memory you’ve allocated but memory leaks still happen all the time.
Human error is inevitable.

The more the compiler can do for you automatically (especially if it’s without performance penalties) the better.



> 
> > […]
>
> Applying break statements is the first thing you should do if you intend
> to break. That way it can't be forgotten.
>
> --
> Thomas Hruska
> CubicleSoft President
>
> I've got great, time saving software that you will find useful.
>
> http://cubiclesoft.com/
>
> And once you find my software useful:
>
> http://cubiclesoft.com/donate/

---

## #100496 — Tony Marston — 2017-09-10T09:23:12+00:00

URL: https://externals.io/message/100487#100496 · In reply to: #100487

wrote in message news:eb28362c-4f8f-45df-bbf0-582e8ad2b8af@Spark...
>
>Hi everybody!
>
>Has this idea been discussed before?
>
>I find myself writing switch statements in PHP quite rarely. This has a few 
>reasons:
>
>1. It doesn’t have a "strict_types” version
>2. It is quite verbose (lots of breaks)
>3. It is a statement rather than an expression
>
>Often, if / elseif statements turn out to be shorter, safer and easier to 
>read than the switch statement.
>What I’d really love is something like a match expression:
>

If there are circumstances where a series of if / elseif statements turn out 
to be shorter, safer and easier to read than a switch statement, then the 
intelligent thing to do would be to use if / elseif statements instead of 
trying to make the switch statement more complicated. If your problem with 
the switch statement is that you sometimes forget to insert a break 
statement then that is your fault. Try to use the language features as they 
were intended to be used and not how you would personally like to use them. 
Millions of other programmers have no problem with the switch statement, and 
they would not be pleased to have it changed just to deal with your 
perceived problem with it.

-- 
Tony Marston

---

## #100497 — ilija.tovilo@me.com — 2017-09-10T09:42:16+00:00

URL: https://externals.io/message/100487#100497 · In reply to: #100496

Hi Tony

> … you sometimes forget to insert a break statement then that is your fault.

Any bug in your source code is ultimately your fault. But as mentioned before human error is inevitable. You can make it easier for your users to make less mistakes though. Other languages (e.g. Rust or Swift) have implicit breaks in their switch statements. This has been done for a reason, I wouldn’t call this a non-issue.

> Millions of other programmers have no problem with the switch statement

It’s all they know. They don’t complain about null pointers even though it’s inventor calls it his billion-dollar mistake. The customer rarely knows what he truly needs.

> they would not be pleased to have it changed just to deal with your perceived problem with it

I don’t suggest altering the behaviour of the switch statement but rather to introduce a new match statement.

Ilija



> wrote in message news:eb28362c-4f8f-45df-bbf0-582e8ad2b8af@Spark...
> > […]
>
> If there are circumstances where a series of if / elseif statements turn out
> to be shorter, safer and easier to read than a switch statement, then the
> intelligent thing to do would be to use if / elseif statements instead of
> trying to make the switch statement more complicated. If your problem with
> the switch statement is that you sometimes forget to insert a break
> statement then that is your fault. Try to use the language features as they
> were intended to be used and not how you would personally like to use them.
> Millions of other programmers have no problem with the switch statement, and
> they would not be pleased to have it changed just to deal with your
> perceived problem with it.
>
> --
> Tony Marston

---

## #100498 — Tony Marston — 2017-09-10T10:22:36+00:00

URL: https://externals.io/message/100487#100498 · In reply to: #100497

wrote in message news:7cd2884a-6606-4c3f-8f95-776fd277878b@Spark...
>
>Hi Tony
>
> > […]
>
>Any bug in your source code is ultimately your fault. But as mentioned 
>before human error is inevitable. You can make it easier for your users to 
>make less mistakes though. Other languages (e.g. Rust or Swift) have 
>implicit breaks in their switch statements. This has been done for a 
>reason, I wouldn’t call this a non-issue.

The problem with implicit breaks is that it makes it impossible to group 
several conditions with a single break. My previous language use implicit 
breaks, and this problem really annoyed me. With PHP I have more control, 
and the fact that I have to insert explicit breaks I do not see as an 
inconvenience.

> > […]
>
>It’s all they know. They don’t complain about null pointers even though it’s 
>inventor calls it his billion-dollar mistake. The customer rarely knows 
>what he truly needs.

They know what they want to achieve, and they have to know which language 
features are available to help them meet their objectives. The fact that 
some language features have turned out to be a big mistake is purely the 
fault of the people who introduced those features. Some programmers complain 
about some languages features even though they are useful features which 
work as advertised as are not deemed to be a mistake - take yourself for 
example who is now complaining about issues with the switch statement.

If what you want to achieve can be done better with a series of if/elseif 
statements than the switch statement, then why can't you use if/elseif 
instead of making the language more complicated?

-- 
Tony Marston

---

## #100499 — ilija.tovilo@me.com — 2017-09-10T10:32:48+00:00

URL: https://externals.io/message/100487#100499 · In reply to: #100498

> it makes it impossible to group several conditions with a single break

In Swift you can group multiple conditions with a comma `,` and in Rust with a pipe `|`. Here’s how that could look in PHP:

```php
match ($x) {
    1, 2: ‘One or two’;
}
```

The only thing you cannot do is this:

```php
switch ($x) {
    case 1:
        echo “One\n”;
    case 2:
        echo “Two\n”;
        break;
}
```

Meaning you cannot “bleed through” the first case into the second, executing both in case of `$x` being `1`. This is acceptable IMO because this looks like a bug even if it’s intended.

>  then why can't you use if/elseif instead of making the language more complicated?

Because that’s usually the perfect use case for a switch statement.



> wrote in message news:7cd2884a-6606-4c3f-8f95-776fd277878b@Spark...
> > […]
>
> The problem with implicit breaks is that it makes it impossible to group
> several conditions with a single break. My previous language use implicit
> breaks, and this problem really annoyed me. With PHP I have more control,
> and the fact that I have to insert explicit breaks I do not see as an
> inconvenience.
>
> > […]
>
> They know what they want to achieve, and they have to know which language
> features are available to help them meet their objectives. The fact that
> some language features have turned out to be a big mistake is purely the
> fault of the people who introduced those features. Some programmers complain
> about some languages features even though they are useful features which
> work as advertised as are not deemed to be a mistake - take yourself for
> example who is now complaining about issues with the switch statement.
>
> If what you want to achieve can be done better with a series of if/elseif
> statements than the switch statement, then why can't you use if/elseif
> instead of making the language more complicated?
>
> --
> Tony Marston

---

## #100500 — Tony Marston — 2017-09-10T11:09:20+00:00

URL: https://externals.io/message/100487#100500 · In reply to: #100499

wrote in message news:3b05768a-95b7-42de-8bb8-3d9ce0cce3a5@Spark...
>
> > […]
>
>In Swift you can group multiple conditions with a comma `,` and in Rust 
>with a pipe `|`. Here’s how that could look in PHP:
>
>```php
>match ($x) {
>    1, 2: ‘One or two’;
>}
>```

Just because other languages have different ways of implementing certain 
features is no reason why PHP should include the same implementations. That 
ius why there are so many different languages - because they do things 
differently. If they were all the same there would be no need for different 
languages.

>The only thing you cannot do is this:
>
>```php
>switch ($x) {
>    case 1:
>        echo “One\n”;
>    case 2:
>        echo “Two\n”;
>        break;
>}
>```
>
>Meaning you cannot “bleed through” the first case into the second, 
>executing both in case of `$x` being `1`. This is acceptable IMO because 
>this looks like a bug even if it’s intended.

For people who RTFM and know how PHP works that code is perfectly acceptable 
and not buggy in the least.

> > […]
>
>Because that’s usually the perfect use case for a switch statement.

So why are you proposing a third alternative to the switch of if/elseif 
statements?

-- 
Tony Marston

---

## #100501 — Dan Ackroyd — 2017-09-10T11:22:25+00:00

URL: https://externals.io/message/100487#100501 · In reply to: #100500

>
> So why are you proposing a third alternative to the switch of if/elseif
> statements?

Because they think it's a good idea.

Not everyone is going to agree, which is why we have voting for RFCs.


cheers
Dan
Ack

---

## #100502 — Rowan Collins — 2017-09-10T14:43:18+00:00

URL: https://externals.io/message/100487#100502 · In reply to: #100487

> Hi everybody!
>
> Has this idea been discussed before?
>
> I find myself writing switch statements in PHP quite rarely. This has a few reasons:
>
> 1. It doesn’t have a "strict_types” version
> 2. It is quite verbose (lots of breaks)
> 3. It is a statement rather than an expression
>
> Often, if / elseif statements turn out to be shorter, safer and easier to read than the switch statement.

I've had the idea kicking around my head for some time of a "switch-use" 
statement. I keep hoping to find the time to play around with the PHP 
parser and see if I can write a proof of concept implementation, just as 
an excuse to get deeper into the source, but since this has come up, 
I'll outline the idea.

The general form would be "switch ( expression ) use ( op ) { ... }", 
where "op" is any binary operator which gives a boolean result, and the 
rest looks the same as a normal PHP switch statement.

The simplest example would be to do a strict comparison by using "===":

switch ( someFunction() ) use ( === ) {
   case 42:
     // ...
   break;
   case '42':
     // ...
   break;
}

Which would approximately de-sugar to:

$temp = someFunction();
switch ( true ) {
   case $temp === 42:
     // ...
   break;
   case $temp === '42':
     // ...
   break;
}

As you can see, the switch(true) version has to use an explicit variable 
to avoid re-computing the expression, which switch does for you, and you 
then have to repeat the "$temp ===", obscuring the fact that all cases 
are checking the same thing. A normal switch, however, can't distinguish 
42 from '42', because it uses the == comparison rules.

If this were the only useful operator, we might just call it "switch 
strict" or something, but here are a couple of examples with other 
operators:

// Generic exception handling function
// Also useful when accepting various incompatible implementations of 
something and wrapping or converting them
switch ( $e ) use ( instanceof ) {
   case FooException:
   case BarException:
     // ...
   break;
   case SomeOtherException:
     // ...
   break;
}

// Dividing a circle into arbitrary sectors, based on this Stack 
Overflow question: https://stackoverflow.com/q/44183771/157957
// Note the ability to place "default" at the top, rather than 
duplicating code in an else clause
switch ( $angle )  use ( <= ) {
   case 30:
   default:
     return Direction::Right;
   break;
   case 60:
     return Direction::UP_RIGHT;
   break;
   case 120:
     return Direction::UP;
   break;
   case 150:
     return Direction::UP_LEFT;
   break;
   case 210:
     return Direction::LEFT;
   break;
   case 240:
     return Direction::DOWN_LEFT;
   break;
   case 300:
     return Direction::DOWN;
   break;
   case 330:
     return Direction::DOWN_RIGHT;
   break;
}


There are a couple of ways to expand this further, if we wanted:

  * Allow operators whose result isn't strictly a boolean, such as bitwise &
  * Allow any 2-parameter callable in place of an operator, to have more
    complex comparisons. With Andrea's "operator functions" suggestion,
    operators would technically just be a subset of this anyway.

The below would be quite useful, but unfortunately preg_match takes 
($pattern, $subject) and this would need ($subject, $pattern), so you'd 
need some extra transform:

switch ( $message ) use ( 'preg_match' ) {
   case '/^Missing parameter:/':
   case '/^Unexpected parameter:/':
     return self::MALFORMED_REQUEST;
   break;
   case '/.*try again later.$/':
     return self::TEMPORARY_ERROR;
   break;
}


Any thoughts?

Regards,

-- 
Rowan Collins
[IMSoP]

---

## #100503 — Theodore Brown — 2017-09-10T16:05:06+00:00

URL: https://externals.io/message/100487#100503 · In reply to: #100487

> I find myself writing switch statements in PHP quite rarely. This has a few reasons:
> 1. It doesn’t have a "strict_types” version
> ...
> I assume that some people will not be so happy about having to switch-like constructs. IMO the implicit type conversion is the biggest issue here. Maybe we could offer a solution for this one at least.

I also rarely use switch, primarily because of the lack of strict comparison.
Personally I would prefer having an option for strict comparison when using switch, similar to how `in_array` has an optional `$strict` parameter.

Would it be possible to add an optional `$strict` parameter to switch? E.g.

```
switch ($i, true) {
    case 1:
        echo 'i is 1';
        break;
    case: 1.0:
        echo 'i is 1.0';
        break;
    case '1':
        echo 'i is "1"';
        break;
    case true:
        echo 'i is true';
        break;
}
```

-Theodore Brown

---

## #100504 — Niklas Keller — 2017-09-10T16:27:56+00:00

URL: https://externals.io/message/100487#100504 · In reply to: #100503

2017-09-10 18:05 GMT+02:00 Theodore Brown <theodorejb@outlook.com>:

> 
>
> > […]
> few reasons:
> > […]
> switch-like constructs. IMO the implicit type conversion is the biggest
> issue here. Maybe we could offer a solution for this one at least.
>
> I also rarely use switch, primarily because of the lack of strict
> comparison.
> Personally I would prefer having an option for strict comparison when
> using switch, similar to how `in_array` has an optional `$strict` parameter.
>
> Would it be possible to add an optional `$strict` parameter to switch? E.g.
>
> ```
> switch ($i, true) {
>     case 1:
>         echo 'i is 1';
>         break;
>     case: 1.0:
>         echo 'i is 1.0';
>         break;
>     case '1':
>         echo 'i is "1"';
>         break;
>     case true:
>         echo 'i is true';
>         break;
> }


I'd very much prefer a "strict switch ($i) { ... }" over a second parameter.

Regards, Niklas

---

## #100506 — Rowan Collins — 2017-09-10T17:45:31+00:00

URL: https://externals.io/message/100487#100506 · In reply to: #100504

> 2017-09-10 18:05 GMT+02:00 Theodore Brown <theodorejb@outlook.com>:
>
> > […]
>
> I'd very much prefer a "strict switch ($i) { ... }" over a second parameter.

What do either of you think of my "switch-use" proposal, which would 
spell this as "switch ($i) use (===)"?

Regards,

-- 
Rowan Collins
[IMSoP]

---

## #100507 — Theodore Brown — 2017-09-10T19:16:47+00:00

URL: https://externals.io/message/100487#100507

> > […]
>
> What do either of you think of my "switch-use" proposal, which would spell this as "switch ($i) use (===)"?

That seems more complicated and confusing than either of the other options. Normally `use()` is for inheriting variables in anonymous functions.

---

## #100508 — lists@rhsoft.net — 2017-09-10T19:22:33+00:00

URL: https://externals.io/message/100487#100508 · In reply to: #100507

Am 10.09.2017 um 21:16 schrieb Theodore Brown:
> 
> 
> > […]
> 
> That seems more complicated and confusing than either of the other options. Normally `use()` is for inheriting variables in anonymous functions.
> 

where did you see `use()` in the proposed SYNTAX?
hint: it's not there

it's just "strict switch" versus "switch"

---

## #100509 — Ryan Pallas — 2017-09-10T19:25:34+00:00

URL: https://externals.io/message/100487#100509 · In reply to: #100508

Am 10.09.2017 um 21:16 schrieb Theodore Brown:

> On Sunday, September 10, 2017 12:45 PM Rowan Collins <
> rowan.collins@gmail.com> wrote:
>
> Would it be possible to add an optional `$strict` parameter to
> > […]
>
> That seems more complicated and confusing than either of the other
> options. Normally `use()` is for inheriting variables in anonymous
> functions.
>
>
where did you see `use()` in the proposed SYNTAX?
hint: it's not there

it's just "strict switch" versus "switch"


Rowan's suggestion included use.

---

## #100510 — lists@rhsoft.net — 2017-09-10T19:35:21+00:00

URL: https://externals.io/message/100487#100510 · In reply to: #100509

Am 10.09.2017 um 21:25 schrieb Ryan Pallas:
> 
> 
> On Sep 10, 2017 1:23 PM, "lists@rhsoft.net <mailto:lists@rhsoft.net>" 
> <lists@rhsoft.net <mailto:lists@rhsoft.net>> wrote:
> 
> 
> 
>     Am 10.09.2017 um 21:16 schrieb Theodore Brown:
> 
>         On Sunday, September 10, 2017 12:45 PM Rowan Collins
>         <rowan.collins@gmail.com <mailto:rowan.collins@gmail.com>> wrote:
> 
>                     Would it be possible to add an optional `$strict`
>                     parameter to
>                     switch? E.g.
>                     ```
>                     switch ($i, true) {
> 
> 
>                 I'd very much prefer a "strict switch ($i) { ... }" over
>                 a second parameter.
> 
> 
>             What do either of you think of my "switch-use" proposal,
>             which would spell this as "switch ($i) use (===)"?
> 
>         That seems more complicated and confusing than either of the
>         other options. Normally `use()` is for inheriting variables in
>         anonymous functions.
> 
> 
>     where did you see `use()` in the proposed SYNTAX?
>     hint: it's not there
> 
>     it's just "strict switch" versus "switch"
> 
> Rowan's suggestion included use

the whole switch discussion is broken by design
with "<?php declare(strict_types=1);" the intention is pretty clear

raise an error if cases are mixed (case 'a' and case 1 und the same 
switch) and also raise an error in a case libe below when $a is anything 
else then int

there is reall yno syntax sugar needed - the first statement of the file 
contains the intention of the developer and yes i migrated a 250000 LOC 
codebase stared in 2003 with PHP4 to PHP7 with strict types for every 
single file

switch($a)
{
  case 1: ..; break;
  case 2: ..; break;
}

---

## #100511 — Rowan Collins — 2017-09-10T20:18:30+00:00

URL: https://externals.io/message/100487#100511 · In reply to: #100507

> On Sunday, September 10, 2017 12:45 PM Rowan Collins 
> <rowan.collins@gmail.com> wrote:
>
> > […]
> parameter.
> > […]
> spell this as "switch ($i) use (===)"?
>
> That seems more complicated and confusing than either of the other 
> options. Normally `use()` is for inheriting variables in anonymous 
> functions.


The choice of "use" as the keyword was largely because it's already a 
reserved word, with multiple meanings in different contexts. As well as 
anonymous functions, it's the keyword for importing names from other 
namespaces, and for including a trait into a class. I would be perfectly 
happy to hear alternative keyword or syntax suggestions.


It might not need a keyword at all, as it could just be "switch ($i ===) 
{ ... }" or "switch ($i) === { ... }", although I'm not that keen on 
either of those.


However, I think using "===" in some form is definitely clearer than ", 
true", which could mean anything; and even "strict" could have multiple 
meanings - for instance, a "strict switch" might be one where "break" 
was mandatory.


Regards,

-- 
Rowan Collins
[IMSoP]

---

## #100512 — Dustin Wheeler — 2017-09-10T20:35:17+00:00

URL: https://externals.io/message/100487#100512 · In reply to: #100511

>
> The choice of "use" as the keyword was largely because it's already a
> reserved word, with multiple meanings in different contexts. As well as
> anonymous functions, it's the keyword for importing names from other
> namespaces, and for including a trait into a class. I would be perfectly
> happy to hear alternative keyword or syntax suggestions.
>

FWIW, within the scope of the suggested "switch-use" feature, I think
that the "use syntax", as suggested by Rowan, feels appropriate. I
agree with the usage based on it already being reserved and used
differently per-context. Additionally, the syntax feels natural and
expresses intent well-enough. All that said, I feel that some form of
strict-switch would be more immediately applicable to a wider
audience. In that regard, I prefer the keyword approach "strict switch
(...) { ... }" rather than using an additional parameter "switch($x,
true)".

-- 
Dustin Wheeler | Software Developer
NC State University
mdwheele@ncsu.edu
"If you don't know where you're going, it's easy to iteratively not get there."

---

## #100513 — Rowan Collins — 2017-09-10T20:35:55+00:00

URL: https://externals.io/message/100487#100513 · In reply to: #100510

> the whole switch discussion is broken by design
> with "<?php declare(strict_types=1);" the intention is pretty clear 

strict_types does not currently have any effect on comparisons anywhere, 
and nor is it likely ever to do so. It is a very specific option, not a 
broad set of behaviours like "use strict" in JS or Perl.

> raise an error if cases are mixed (case 'a' and case 1 under  the same switch)

It's interesting that the behaviour you think is obvious is completely 
different to what I think of: if the author of the code has put both 
case 42 and case '42' in the switch statement, the "strict" 
interpretation in my mind would be that both branches are reachable, as 
though tested with an "===" operator (whereas currently the second would 
never be selected, because no value =='42' that doesn't also ==42).


> and also raise an error in a case like below when $a is  anything else then int

I guess this explains the different direction you're coming from: what 
you want could perhaps be termed a "strongly typed switch statement", 
where both input and case values are checked as soon as possible for 
being of some specified type.

The logical syntax for that would probably be an explicit type in the 
switch statement somewhere, like this:

switch(int $a)
{
  case 1: ..; break;
  case 2: ..; break;
}

Although an obvious question would be why switch gets such a version, 
and what other language constructs should follow suit.

Regards,

-- 
Rowan Collins
[IMSoP]

---

## #100514 — lists@rhsoft.net — 2017-09-10T23:36:23+00:00

URL: https://externals.io/message/100487#100514 · In reply to: #100513

Am 10.09.2017 um 22:35 schrieb Rowan Collins:
> 
> > […]
> 
> strict_types does not currently have any effect on comparisons anywhere, 
> and nor is it likely ever to do so. It is a very specific option, not a 
> broad set of behaviours like "use strict" in JS or Perl.

in case of a normal comparison you have !== and === to make it explicit

> > […]
> 
> It's interesting that the behaviour you think is obvious is completely 
> different to what I think of: if the author of the code has put both 
> case 42 and case '42' in the switch statement, the "strict" 
> interpretation in my mind would be that both branches are reachable, as 
> though tested with an "===" operator (whereas currently the second would 
> never be selected, because no value =='42' that doesn't also ==42).

yes, for non-strict code that's fine

> > […]
> 
> I guess this explains the different direction you're coming from: what 
> you want could perhaps be termed a "strongly typed switch statement", 
> where both input and case values are checked as soon as possible for 
> being of some specified type.

yes, that's what i expect from declare(strict_types=1); wherever it is 
possible for several reasons

* as developer i like fail early and raise a clear exception
* in the best case even at compile time and not 3 days later at runtime
* it makes code often more secure over time when it points
   out missing input validation and from where a bad value comes
   instead burry a error where it triggers the exception
* it enables optimizations like 7.1 got a lot
* it even may help a future JIT to optimize

due change every code i wrote to strict-types and enhance every function 
to type-hints and return types i found a ton of hidden probably bugs and 
especially fuzzying points out code weakness

> The logical syntax for that would probably be an explicit type in the 
> switch statement somewhere, like this:
> 
> switch(int $a)
> {
>   case 1: ..; break;
>   case 2: ..; break;
> }

i like that!

> Although an obvious question would be why switch gets such a version, 
> and what other language constructs should follow suit.

well, you have to start somewhere and the start was done with 7.0 for 
function params and return types, switch is an obvious  place that could 
be enhanced and the syntax above is 100% consistent to function params

it's not only consistent in the syntax, it's also consistent in behavior 
meaning in no-strict-mode make a implicit type cast and it's not a new 
syntax element

currently i have no other language constrcuts in mind but i think 
starting here could lead in people point out other places where it makes 
sense and since it's completly opt-in it don't break any existing code

ok, i have one in mind
foreach($arr as int $x)

raise a runtime error when you expect a array with only numbers and the 
comes '42' and in strict-mode do a consistent implicit cast in 
non-strict where you can be sure in both cases that you deal with a int 
within the loop
