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条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程