PHP switch 语句不使用 return 执行值
问题描述:
PHP switch 语句是否有可能在使用 return 时没有执行 switch 所需的结果?
Is it possible that PHP switch statement does not executes the switch desired result while using return?
这两种说法有什么区别?
What is the difference between these two statements?
$foo = '2';
switch ($foo) {
case 1:
echo 1;
break;
case 2:
echo 2;
break;
}
执行 2
对比
$foo = '2';
switch ($foo) {
case 1:
return 1;
break;
case 2:
return 2;
break;
}
似乎不起作用.
有没有办法让它工作?
答
这里是如何在函数中使用 case 语句 -
Here is how to use a case statement in a function -
function myFunction($foo) {
switch ($foo) {
case 1:
return 1;
break;
case 2:
return 2;
break;
default:
return 'no matching values were sent to the function';
break;
}
}
echo myFunction(2); // will echo '2'
在这样的函数中,你不需要 break 语句,return
负责中断.这只是很好的做法.您应该养成在开关中使用默认情况的习惯,即使您仅使用它们将错误记录到日志或类似内容中.
In functions like this you do not need to have the break statements, the return
takes care of the breaking. It is just good practice. You should get in the habit of using default cases in your switches, even if you only use them to record an error to a log or something similar.