Home  >  Article  >  Backend Development  >  Practical switch commands in PHP

Practical switch commands in PHP

DDD
DDDOriginal
2023-10-09 10:26:351163browse

Ensure well-structured Switch commands in PHP

In PHP, the switch statement is the control program A powerful tool for workflows, especially when dealing with multiple conditional branches. However, achieving clean and efficient conversions comes with its own obstacles. This article explores basic tips and practices for checking the quality of the "switch" command to ensure code quality and optimize its performance.

Missing default entry

The first thing to consider is the switch statement Whether to include the default case. Adefault acts as a fallback option, ensuring that code is executed when there is no defined case match.

default should always be present. In fact, the command match is an alternative version of switch, when it fails to match anythingcase, and default is missing, it throws an exception.

<?php
switch($a) {
    case 0:
      echo &#39;A&#39;;
      break;
       
    case 1:
      echo &#39;A&#39;;
      break;
}
 
?>

default Serves a different purpose:

  • All other cases together deal with. This is when a limited list of cases is available, and anything outside of that list can be handled in a single way.
  • Raises an error if reached. In this case, the preceding context switch ensures that a limited list of cases is processed. Then, an exception should be thrown whenever a situation other than a legal situation reaches the command.
<?php
switch($a) {
    case 0:
      echo &#39;A&#39;;
      break;
       
    case 1:
      echo &#39;A&#39;;
      break;
       
    default:
      throw new MyException(&#39;This should be zero or one&#39;);
}
 
?>

Always make sure the switch has a default value.

重复案例

检查switch陈述中是否有重复案例是有回报的。PHP 只处理它遇到的第一种情况,忽略其他情况。这会导致死代码,开关中的一些分支将被忽略并且永远不会被使用。

<?php
switch($a) {
    case &#39;gif&#39;:
        // doSomething() and break
       
    case &#39;jpeg&#39;:
    case &#39;jpg&#39;:
        // doSomething() and break
 
    case &#39;png&#39;:
        // doSomething() and break
 
    case &#39;gif&#39;:
        // doSomething() and break
       
    default:
      throw new MyException(&#39;This should be an image format&#39;);
}
 
?>

重复的情况经常发生在很长的案例列表中。

当实际值被常量名称或 PHP 的类型杂耍隐藏时,也会发生这种情况。确实,switch使用了宽松的比较风格,有些文字实际上可能是相同的。

<?php
 
// $a in [null, false, &#39;&#39;, 0]
switch($a) {
    // Most of the cases ends here, except 0
    // because it is the first encountered
    case &#39;&#39;:
        print &#39;Empty string&#39;;break;
 
    // 0 goes here
    case 0:
        print &#39;Zero&#39;;break;
       
    case false:
        print &#39;false&#39;;break;
 
    case null:
        print &#39;null&#39;;break;
       
    default:
      throw new MyException(&#39;This should be empty&#39;);
}
 
?>

仔细检查案例值并删除重复项。

重复的代码块

另一个常见问题是不同 case 分支中的代码块重复。这种冗余会使您的系统变得臃肿switch,并且使将来的更新变得困难。考虑重构代码以消除重复并合并案例。

<?php
 
switch($a) {
    case &#39;john&#39;:
        $b = 0; break;
 
    case &#39;henry&#39;:
        $b = 10; break;
 
    // duplicate of case &#39;john&#39;
    case &#39;julia&#39;:
        $b = 0; break;
 
    case &#39;jeroen&#39;:
        $b = 30; break;
       
    default:
      throw new MyException(&#39;This is an unexpected name&#39;);
}
 
?>

枚举案例的使用

PHP 内置了对枚举的支持。枚举的重要优点之一是其有限性。它们代表选项的完整集合,并且不存在其他选项。这使得检查 a 是否switch涵盖了所有可能的情况变得很容易。

<?php
 
enum formats {
    case GIF;
    case JPG;
    case PNG;
}
 
switch($a) {
    case formats::GIF:
        // doSomething() and break;
 
    case formats::PNG:
        // doSomething() and break;
         
    // We are missing one case : JPG!
 
    // Unknown cases triggers an exception lazily (only if reached)
    case formats::TIFF:
        // doSomething() and break;
 
    default:
      throw new MyException(&#39;Unknown image format&#39;);
}
 
?>

通过简单开关进行优化

PHP 7.2 引入了针对switch.

在此之前,PHP 会逐个检查每个案例,并在找到匹配值后立即停止。在 PHP 7.2 及更高版本中,当大小写值是简单文字时,PHP 会为它们设置一个查找表。然后,PHP 立即跳转到正确的情况,并绕过所有其他不匹配的情况。

<?php
 
switch($a) {
    case 1:
        // doSomething() and break;
 
    case 2:
        // doSomething() and break;
         
    default:
      throw new MyException(&#39;Unknown image format&#39;);
}
 
?>

当所有情况都是简单值时,就会发生简单切换,可以直接与传入变量进行比较。

如果开关混合了表达式和简单值,建议将简单文字放在第一个开关中switch,并将其他文字放在第二个开关中。

<?php
 
switch($a) {
    case 1:
        // doSomething() and break;
 
    case 2:
        // doSomething() and break;
         
    default:
        switch($a) {
            case $b + 2:
                // doSomething() and break;
 
        case strtolower($a):
            // doSomething() and break;
         
        default:
            throw new MyException(&#39;Unknown case&#39;);
    }
}
 
?>

以不同的方式处理它们也可能更方便,例如使用先前的条件。

Summary

In short, switchwell-structured statements in PHP can greatly improve the clarity of the code degree, maintainability and performance. By checking for missing default entries, eliminating duplicate cases and blocks of code, leveraging enum-like structures, and optimizing complex switches, you can ensure that your statements are still switchAn efficient and effective part of any PHP code base.

The above is the detailed content of Practical switch commands in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn