On Sun, 20 Oct 2019 at 22:35, Mike Schinkel <m...@newclarity.net> wrote:
> What restriction are you referring to? The forced `default` or the > semi-colon being required? > > Neither; I was referring to not being able to put a switch expression as a statement on its own, which Kosit has explained is a limitation of the parser. > I would much prefer to use a switch for multiple, mutually exclusive cases > no matter what how complex the expression is because with a switch the > cases expressions line up vertically. With `if` and `else if` it is harder > to vertically eyeball the different mutually exclusive cases. > I've never particularly been bothered by it, but wouldn't adding four spaces in your "if" statement make it line up with all your "elseif" statements? > The "return" case in particular seems ambiguous - if $v is visible outside > the function, will it have a value assigned to it by the "return" branch, > and if so what would that value be? > > > It should have its prior value, since the expression did not complete. > > Alternately we could choose to always assign it null on return or break. > > But how often will we have this use-case? Only for global variables, > which hopefully will eventually become extinct in userland code. > > Not just global variables, no; it could be assigning an object property ($this->foo = switch($x){ case 1 => return 1; }) for instance. It could also be in the argument for a function call ( doSomething(switch($x){ case 1 => return 1; }) ) in which case presumably the function would not be called at all? Overall, having a "return" in the middle of an expression would be very confusing, I think. > That said, we should almost be able to do *both*, and just let PHP throw > an error if there is a problem. This would be useful if you know 100% that > the code won't fail because of the code that came before it: > > if ( is_numeric($_GET['id'] ?? 0 ) ) { > $id = intvar($_GET['id'] ?? 0); > > $user = getUser(<int>$id): > > } > > I'm not sure what the point of this example is. You've just cast to int, so the assertion can never fail, and if getUser has a type hint, it's about to make that assertion anyway. Regards, -- Rowan Tommins [IMSoP]