Jump to content
Larry Ullman's Book Forums

Recommended Posts

I've never seen this variation of the switch statement, could you guys please comment on it?

 

 

switch ($language) {
case 'German':
echo 'Hallo, Welt!';
break;
case 'Italian':
echo 'Ciao, mondo!';
break;
case 'Spanish':
echo 'Hola, mundo!';
break;
case 'English':
default:
echo 'Hello, world!';
break;
}

 

What surprised me is the last four lines:

 

 

case 'English':
default:
echo 'Hello, world!';
break;

 

I thought the default should be set without mentioning the case before. Is that a legitimate way of doing things or just a typo in the book?

Link to comment
Share on other sites

I'm not sure how intentional that code was on Larry's part, but it is 100% legitimate and possible, so that's not an issue.

 

With that said, I tend to agree with you in that I would probably just remove the "case 'English':" line, as the code does the exact same thing with or without it. Because there is no code (or more importantly, no break statement) between the English case and the default, writing your code like you suggested is perfectly legitimate.

 

Hopefully Larry will comment as well, as he's the one who wrote it.

  • Upvote 1
Link to comment
Share on other sites

Yes, Antonio does make a good point, but for me, it's always a judgment call of how explicit I need to be in my code for future-proofing reasons at the sake of having to write more code now.

In this one particular case, having the English case seems a bit too verbose, but maybe that's just me.

 

Also, Dimitri, it's ハートリー. Nice try though!

  • Upvote 1
Link to comment
Share on other sites

It's entirely purposeful on my part. It's called a "fall through" and allows you to have the same result for more than one case. I would argue that having the English case in there is absolutely necessary, as it does not do the same thing as the default. They both have the same end result, yes, but one case applies for one of the most popular languages in the world (in this hypothetical example) and the other case applies when no value or no valid value is supplied. Those are two different scenarios, which is why two different cases are used, even if they have the same result.

  • Upvote 1
Link to comment
Share on other sites

I can appreciate that perspective, Dimitri, but this is an advanced PHP book and I do have to make assumptions as to what I would expect the reader to know at this point, such as the usage of a control structure. What is confusing to, or unknown by, one reader is common knowledge to another. You might complain that this wasn't explained and you thought it was an error, but another reader will complain if I had walked through the explanation because that reader will think it's too basic for an advanced PHP book.

 

These are the balances and decisions writers have to make.

Link to comment
Share on other sites

 Share

×
×
  • Create New...