在PHP中切换case语句

时间:2016-06-17 12:20:31

标签: php

我正在学习PHP。我从网站下载了一个开源项目,并查看该项目中每个模块的工作流程。我注意到一个我不熟悉的开关盒。

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

以上补丁就是我的样子。 当我提供输入时:

$value = 'student';

返回 StudentClass 实例。

如果我给

$value = 'teacher';

然后返回 TeacherClass 实例。

如果有人解释这个流程,那么对我更好地理解PHP会很有帮助

2 个答案:

答案 0 :(得分:5)

您的字符串cases没有breakreturn条款,因此它们会“落到”下一个case。此外,您的break在此处没有任何用途。

我在您的代码中添加了注释,以解释发生了什么。

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
}

此外,PHP明确允许在;之后使用分号(case),但通常不认为它是好的样式。 From the docs:

  

在案例之后可以使用分号而不是冒号......

答案 1 :(得分:0)

Switch语句用于根据不同的条件执行不同的操作。

首先,我们有一个表达式n(通常是一个变量),它被评估一次。然后将表达式的值与结构中每个案例的值进行比较。如果存在匹配,则执行与该情况相关联的代码块。使用break来防止代码自动进入下一个案例。如果未找到匹配项,则使用默认语句。



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;
}




相关问题