简体   繁体   English

PHP-带有例外的转换案例

[英]PHP - Switch Case with Exceptions

I am wondering if I should include break in my switch even if a case is throwing an exception. 我想知道即使案件引发异常,我是否也应该在开关中加入break

switch ($key) {
    case self::ABC:
    case self::CBA:
        if (!is_string($key)) {
            throw new Exception('Well.. this should be a string my friend');
        }
        break;
}

Am I even getting to the break? 我什至要休息吗? I do not think so, so why should I include it? 我不这么认为,所以为什么要包括它呢? Does it makes sense? 有道理吗?

If self::CBA is a string, then the exception won't be thrown and your code will reach to break. 如果self::CBA是字符串,则不会引发异常,并且您的代码将中断。 If that case is the last case in your switch, then break may not be needed as the switch will end anyways, but it is better to just add break instead of not adding it, it's one line of code that can save you a lot of trouble from executing codes that were not meant to be executed. 如果这种case是交换机中的最后一种情况,则可能不需要中断,因为交换机无论如何都会结束,但是最好添加break而不是不添加break ,这是一行代码,可以节省很多时间由于执行了本不应该执行的代码而造成的麻烦。 I know this the hard way. 我知道这很难。

By adding break to all cases, you can rearrange the cases without any problems in the future and you would also get into the habit of writing break every time you write a switch statement (it's a good habit). 通过在所有案例中添加break,您可以在将来没有任何问题的情况下重新安排案例,并且您还将养成每次编写switch语句时都编写break的习惯(这是一个好习惯)。 I hope it answers your question. 我希望它能回答您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM