-1

Let's say I have a switch statement like this:

switch($myVar)
{
    case 'A':
        $special = 1;
        $total = $special + 5;
        break;

    case 'B':
        $special = 2;
        $total = $special + 5;
        break;

    case 'C':
        $special = 3;
        $total = $special + 5;
        break;
}

As you can see above, the only thing that differs from the cases of my switch statement is the variable $special. Its value should be 1 if case is A and 2 if case is B and so on. Apart from that the rest of the code after that stays the same. Is there a way that I can organize this switch statement to remove the duplicate code:

$total = $special + 5

Thank you

4

5 に答える 5

3

Move the duplicate code to after the switch.

switch($myVar)
{
    case 'A':
        $special = 1;
        break;

    case 'B':
        $special = 2;
        break;
    default:
        $special = 0; //setup a default value to prevent undefined $special errors.
}

$total = $special + 5;
于 2012-11-29T18:35:56.917 に答える
2

Why not

$special = ('A' == $myVar ? 1 : 2);
$total = $spacial + 5;

EDIT

As the question has changed, here is an update

$lookup = array( 'A' => 1, 'B' => 2, 'C' =>3); // You can just initialize this once
                                               // maybe a static variable of a class etc.
$special = $lookup[$myVar];
if (!isset($special)) { $special = /* Some default value */ }; // If this is necessary
$total = $special + 5;
于 2012-11-29T18:36:34.587 に答える
2
switch($myVar)
{
    case 'A':
        $special = 1;
        break;

    case 'B':
        $special = 2;
        break;
}

$total = $special + 5;

you could put it once after the switch block. You don't have to repeat this code since it will occur anyway, if you put it after the switch statement.

于 2012-11-29T18:36:35.310 に答える
2

How about the following way ?

$special = array(
    'A' => 1,
    'B' => 2
);

$total = ($special[$myVal] || 0) + 5;
于 2012-11-29T18:42:15.857 に答える
1
switch($myVar) {
    case 'A':
        $special = 1;
        break;
    case 'B':
        $special = 2;
        break;
    default:
        $special = 0;
}
$total = $special + 5;
于 2012-11-29T18:36:01.233 に答える