Jay Venkat
Jay Venkat

Reputation: 397

Switch case statement in PHP

I am learning PHP. I have downloaded an open source project from a website and looking the workflow of each modules in that project. I noticed a switch case which is unfamiliar to me.

switch ($value) {
        case 'student':
        case StudentClass::getInstance()->getId();
            return new StudentClass();
            break;
        case 'teacher':
        case TeacherClass::getInstance()->getId();
            return new TeacherClass();
            break;
        default:
            break;
    }

The above patch is what I looked. When I give input:

$value = 'student';

It returns StudentClass instance.

If I give

$value = 'teacher';

then it returns TeacherClass instance.

If anyone explain the flow, it will be helpful to me to understanding PHP much better

Upvotes: 0

Views: 3373

Answers (2)

Sanjay Dhiman
Sanjay Dhiman

Reputation: 68

Switch statement is used to perform different actions based on different conditions.

First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

switch (n) {
    case label1:
        code to be executed if n=label1;
        break;  // if n=label1,break ends execution and exit from switch
    case label2:
        code to be executed if n=label2;
        break;  // if n=label2,break ends execution and exit from switch
    case label3:
        code to be executed if n=label3;
        break;  // if n=label3,break ends execution and exit from switch
    ...
    default:
        code to be executed if n is different from all labels;
}

Upvotes: 0

elixenide
elixenide

Reputation: 44833

Your string cases don't have break or return statements, so they "fall through" to the next case. Also, your breaks don't serve any purpose here.

I've added comments to your code to explain what's happening.

switch ($value) {
        case 'student': // keeps going with next line
        case StudentClass::getInstance()->getId();
            return new StudentClass(); // handles both cases above
            break; // unnecessary because of the return above
        case 'teacher': // keeps going with next line
        case TeacherClass::getInstance()->getId();
            return new TeacherClass(); // handles both cases above
            break; // unnecessary because of the return above
        default:
            break; // pointless, but handles anything not already handled
}

Also, PHP explicitly allows use of a semicolon (;) after a case, but it is not generally considered good style. From the docs:

It's possible to use a semicolon instead of a colon after a case...

Upvotes: 6

Related Questions