Книга: Fedora™ Unleashed, 2008 edition

Switching

Switching

Having multiple if statements in one place is ugly, slow, and prone to errors. Consider the code in Listing 27.3.

LISTING 27.3 How Multiple Conditional Statements Lead to Ugly Code

<?php
 $cat_age = 3;
 if ($cat_age == 1) {
  echo "Cat age is 1";
 } else {
  if ($cat_age == 2) {
   echo "Cat age is 2";
  } else {
   if ($cat_age == 3) {
    echo "Cat age is 3";
   } else {
    if ($cat_age == 4) {
     echo "Cat age is 4";
    } else {
     echo "Cat age is unknown";
    }
   }
  }
 }
?>

Even though it certainly works, it is a poor solution to the problem. Much better is a switch/case block, which transforms the previous code into what's shown in Listing 27.4.

LISTING 27.4 Using a switch/case Block

<?php
 $cat_age = 3;
 switch ($cat_age) {
 case 1:
  echo "Cat age is 1";
  break;
 case 2:
  echo "Cat age is 2";
  break;
 case 3:
  echo "Cat age is 3";
  break;
 case 4:
  echo "Cat age is 4";
  break;
 default:
  echo "Cat age is unknown";
 }
?>

Although it is only slightly shorter, it is a great deal more readable and much easier to maintain. A switch/case group is made up of a switch() statement in which you provide the variable you want to check, followed by numerous case statements. Notice the break statement at the end of each case. Without that, PHP would execute each case statement beneath the one it matches. Calling break causes PHP to exit the switch/case. Notice also that there is a default case at the end that catches everything that has no matching case.

It is important that you do not use case default: but merely default:. Also, it is the last case label, so it has no need for a break statement because PHP exits the switch/case block there anyway.

Оглавление книги


Генерация: 1.152. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз