Do you need break in switch when return is used?

后端 未结 8 1763
温柔的废话
温柔的废话 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: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.

提交回复
热议问题