douhuanqiao5290 2016-06-17 12:20
浏览 21
已采纳

在PHP中切换case语句

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

  • 写回答

2条回答 默认 最新

  • dpjr86761 2016-06-17 12:27
    关注

    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...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?