Christian Stoller wrote (on 25/09/2014):
From: Rowan Collins [mailto:rowan.coll...@gmail.com], Sent: Thursday, September 
25, 2014 12:31 PM
Sorry, I was talking about this bit:

Currently, switch always uses a "loose" comparison (==), so cannot
distinguish between "case 3" and "case 3.0". Occasionally, it would be
nice to switch on a strict comparison (===); but then I thought, why
stop there? What if you could use switch with any comparison operator?

My idea is to give the switch() statement an optional "use" clause
(since that's an existing keyword) containing a single comparison operator
See my earlier e-mail for examples and further details. Maybe I should
have given it its own thread so it was more visible; the idea has been
brewing for a while, I just thought this thread was a convenient place
to mention.
Ah, okay, sorry.
What do you think about that:

$value = 3;
switch (true) {
    case 3.0 === $value: break;
    case 3 < $value: break;
    case 3 > $value: break;
}

Christian

When mixing operators like that, it makes sense to use that style - although if you're not using fallthrough, there is little advantage over if/elseif/else:

$value = 3;
if ( 3.0 === $value ) { }
elseif ( case 3 < $value ) { }
elseif ( case 3 > $value ) { }


At the end of the day, all control structures are glorified conditional jumps, and most switch statements are glorified if/else blocks. To take one of my examples from last night, you could write:

if ( $product instanceOf ProductInterfaces\Flight ) {
    // ...
}
elseif ( $product instanceOf ProductInterfaces\Accomm ) {
    // ...
}
else {
    // ...
}

Clearly, this works, as would the same thing using switch(true) and case instead of if/elseif, but the "$product instanceOf" has to be copied into every clause, and someone reading the code cannot assume that all the clauses are performing the same test.

In my proposed version, the intent is expressed more clearly, and there is less risk of a bug being introduced by incorrect copying or refactoring:

switch ( $product ) use ( instanceOf ) {
    case ProductInterfaces\Flight:
        // ...
    break;
    case ProductInterfaces\Accomm:
        // ...
    break;
    default:
        // ...
}

That's the idea anyway.
--
Rowan Collins
[IMSoP]

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

Reply via email to