Do you need break in switch when return is used?

后端 未结 8 1785
温柔的废话
温柔的废话 2021-01-30 18:56

I was wondering if I need to use \"break\" in \"switch\" function when \"return\" is used.

function test($string)
{
  switch($string)
  {
    case \'test1\':
            


        
相关标签:
8条回答
  • 2021-01-30 19:39

    You do not need a break, the return stops execution of the function.

    (for reference: http://php.net/manual/en/function.return.php says:

    If called from within a function, the return() statement immediately ends execution of the current function

    )

    0 讨论(0)
  • 2021-01-30 19:39

    Break is just a cautionary statement used to limit the control of switch stucture from going into another case...for example if you have three case statements and value is for first case and you have used case without any break structure then all the following cases will be executed inspite of the condition being satisfied only for the first case... Return can perform the asme function so it won't be a problem if you use return in place of break because return will take control away from the switch case statement which is the need at that moment...... hope it helps....

    0 讨论(0)
  • 2021-01-30 19:41

    Yes, you can use return instead of break...

    break is optional and is used to prevent "falling" through all the other case statements. So return can be used in a similar fashion, as return ends the function execution.

    Also, if all of your case statements are like this:

    case 'foo':
       $result = find_result(...);
       break;
    

    And after the switch statement you just have return $result, using return find_result(...); in each case will make your code much more readable.

    Lastly, don't forget to add the default case. If you think your code will never reach the default case then you could use the assert function, because you can never be sure.

    0 讨论(0)
  • 2021-01-30 19:41

    No, you don't need a break in a switch case statement. The break is actually optional, but use with caution.

    0 讨论(0)
  • 2021-01-30 19:44

    You don't need it, but I would strongly advise using it in any case as good practice.

    0 讨论(0)
  • 2021-01-30 19:44

    return gives the control back to the calling method, where as break jumps to the first instruction after the switch block.

    0 讨论(0)
提交回复
热议问题