在switch分支中使用return可以替代break

  • Post author:
  • Post category:其他


例子:

1、

$a =1;

function test($a){


switch($a){


case 1:echo 1;

case 2:echo 2;

default:echo ‘default’;

}

}

echo test($a);

result:

12default

2、

$a =1;

function test($a){

switch($a){

case 1:return 1;

case 2:return 2;

default:echo ‘default’;

}

}

echo test($a);

result:

1

第一个例子,没有使用break,所以转到对应case项时,不会中断而会继续执行第二个case项;

第二个例子,也没有使用break,但是使用了return,return的作用是历时中断函数并返回return值,在只有switch的函数中,return在中断效果上和break是一致的。

结论:在只有switch的函数中,在switch分支中使用return可以替代break



版权声明:本文为ownfire原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。