Page 94 - Beginning PHP 5.3
P. 94
Part II: Learning the Language
Note that each case construct has a break statement at the end of it. Why are these break statements
necessary? Well, when the PHP engine finds a case value that matches the expression, it not only
executes the code block for that case statement, but it then also continues through each of the case
statements that follow, as well as the final default statement, executing all of their code blocks in turn.
What ’ s more, it does this regardless of whether the expression matches the values in those case
statements! Most of the time, you don ’ t want this to happen, so you insert a break statement at the end
of each code block. break exits the entire switch construct, ensuring that no more code blocks within
the switch construct are run.
For example, if you didn ’ t include break statements in this example script, and $userAction was equal
to ”open” , the script would open the file, save the file, close the file, log the user out and, finally, display
“ Please choose an option ”, all at the same time!
Sometimes, however, this feature of switch statements is useful, particularly if you want to carry out an
action when the expression matches one of several different values. For example, the following script
asks the users to confirm their action only when they ’ re closing a file or logging out:
switch ( $userAction ) {
case “open”:
// Open the file
break;
case “save”:
// Save the file
break;
case “close”:
case “logout”:
print “Are you sure?”;
break;
default:
print “Please choose an option”;
}
If $userAction equals ”open” or ”save” , the script behaves like the previous example. However, if
$userAction equals ”close” , both the (empty) ”close” code block and the following ”logout” code
block are executed, resulting in the “ Are you sure? ” message. And, of course, if $userAction equals
”logout ”, the “ Are you sure? ” code is also executed. After displaying “ Are you sure? ” the script uses a
break statement to ensure that the default code block isn ’ t run.
Compact Coding with the Ternary Operator
Although you looked at the most common PHP operators in the previous chapter, there is another
operator, called the ternary operator , that is worth knowing about. The symbol for the ternary operator is ? .
Unlike other PHP operators, which work on either a single expression (for example, !$x ) or two
expressions (for example, $x == $y ), the ternary operator uses three expressions:
( expression1 ) ? expression2 : expression3;
56
9/21/09 8:52:07 AM
c04.indd 56
c04.indd 56 9/21/09 8:52:07 AM