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

来源:互联网 发布:魔抓软件 编辑:程序博客网 时间:2024/05/29 15:37

例子:

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


原创粉丝点击