PHP 编码样式返回;在开关/情况下
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1437461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Coding styles return; in switch/case
提问by opHASnoNAME
we're trying to implement new coding style guidelines for our team, the php codesniffer is printing an warning on switch case statements when no "break" is found like:
我们正在尝试为我们的团队实施新的编码风格指南,当没有找到“中断”时,php 代码嗅探器会在 switch case 语句上打印警告,例如:
switch ($foo) {
case 1:
return 1;
case 2:
return 2;
default:
return 3;
}
is there any good reason to use :
有什么好的理由使用:
switch ($foo) {
case 1:
return 1;
break;
}
?? the break is never reached ?
?? 休息从未达到?
回答by John Carter
It's perfectly valid to leave out the breakwhen you returnfrom a switch.
这是完全有效的离开了break,当你return从一个switch。
But it's fairly common practise to add explicit breaks to every caseas a defensive programmingpractise.
但是将显式breaks添加到 eachcase作为防御性编程实践是相当普遍的做法。
switch ($foo) {
case 1:
return 1;
break;
case 2:
return 2;
break;
}
The idea is that should you later change your code in case 1and remove the return statement, you could forget to add a break.
这个想法是,如果您稍后更改代码case 1并删除 return 语句,您可能会忘记添加break.
That would accidentally cause program flow to fall through to case 2.
这会意外地导致程序流落入case 2.
switch ($foo) {
case 1:
somethingDifferent();
case 2:
return 2;
break;
}
Falling through case statements is slightly unusual and you should add a comment to your code when you do it to show that it's intentional.
通过 case 语句有点不寻常,您应该在执行此操作时在代码中添加注释以表明它是故意的。
switch ($foo) {
case 1:
somethingDifferentAndWeWantToDoCase2AsWell();
// fallthrough
case 2:
return 2;
break;
}
As with many defensive programming practises you've got to balance whether the code bloat - which potentially clutters your code and make it less readable - is worth it or not.
与许多防御性编程实践一样,您必须平衡代码膨胀(这可能会使您的代码混乱并降低其可读性)是否值得。
回答by Chemaclass
If your "php codesniffer is printing a warning" try to get another better codesniffer and don't forget to try to use the last PHP stable version. You can, of course, write a breakafter one return, but it doesn't make sense, because it will never be read at all. Your code is OK.
如果您的“php 代码嗅探器正在打印警告”,请尝试使用另一个更好的代码嗅探器,并且不要忘记尝试使用最新的 PHP 稳定版本。当然,你可以写一个breakafter one return,但这没有意义,因为它永远不会被读取。你的代码没问题。
Look at this:
看这个:
$fun = function(int $argument): string {
switch ($argument) {
case 1:
return "one";
case 2:
return "two";
default:
return "more than two";
}
};
$str = $fun(4); // return "more than two"
In my opinion, this is simpler and better: fewer lines => less code to maintain :-)
在我看来,这更简单更好:更少的行 => 更少的代码维护:-)
回答by Lavkush
I have much better solution.Please follow below code for above switch statment:
我有更好的解决方案。请按照以下代码查看上述开关语句:
$result = 3; // for default case
switch ($foo) {
case 1:
$result = 1;
break;
case 2:
$result = 2;
break;
default:
// do nothing
}
return $result;
It will not result in any error and code is also fine with concepts.
它不会导致任何错误,并且代码对概念也很好。
回答by James
To answer your question, no there's no good reason to have something that does nothing. Think about it this way, a comment after the returninstead of a breaksaying "don't forget" will have the same affect - none. And put that way it sounds silly, right?
要回答您的问题,没有充分的理由去做一些什么都不做的事情。这样想一想,在 之后的评论return而不是break说“不要忘记”将具有相同的影响 - 没有。这么说听起来很傻,对吧?
Unless you need to set a var to use later, I'd suggest the approach you have is perfectly fine. I knew the code's intent within 2 seconds from looking at it. Having a breakjust creates confusion.
除非您需要设置一个 var 以供以后使用,否则我建议您采用的方法非常好。我在查看代码的 2 秒内就知道代码的意图。有一个break公正会造成混乱。
There is no one size fits all really. The correct approach depends on whichever fits the scenario. Set a variable in each caseand having a breakmay be the right way, or perhaps just return makes sense.
没有一种尺寸适合所有人。正确的方法取决于适合场景的方法。在每个变量中设置一个变量case并使用 abreak可能是正确的方法,或者也许只是 return 有意义。
Some observations on other suggestions made in answers:
对答案中其他建议的一些观察:
1)Not having a breakafter returnmeans problems could arise if code is later changed
1)没有breakafterreturn意味着如果以后更改代码可能会出现问题
Whenever possible, code should be explicit, as well as readable and clear. We can also code in a way to make future changes easier. But in something as simple as a switchit should be no problem and need no safety net to refactor a caselater to add or remove a returnor break.
只要有可能,代码应该是明确的,以及可读和清晰的。我们还可以通过某种方式编写代码,使将来的更改更容易。但是在像 aswitch这样简单的事情中,它应该没问题,并且不需要安全网来重构 acase以后添加或删除 areturn或break。
In fact, if you removed a returnand "didn't notice there was no break" then that's a poor mistake and could be made in any part of coding. No gotcha checking will save you from that. And one should be very careful coding for future potentials, as that potential may never happen, or something else may happen, and you just end up maintaining obsolete code for years.
事实上,如果您删除了 areturn并且“没有注意到没有break”,那么这是一个糟糕的错误,并且可能在编码的任何部分发生。没有任何问题检查可以让你免于这一点。并且应该非常小心地为未来的潜力编码,因为这种潜力可能永远不会发生,或者其他事情可能会发生,而你最终只会维护过时的代码多年。
In the same vein this was argued to be a safety net for future changes - What if you remove the returnand accidentally left in that safety net breakwhen you should have removed it?
同样,这也被认为是未来变化的安全网——如果你在本应该移除它的时候把它拿掉了return,但不小心留在了那个安全网里break怎么办?
Even if this switch statement was a life or death scenario, really serious code, I would be against adding the "pointless" break after the return. Just make sure whoever was working on the code knew what they were doing, and it was code reviewed by enough eyes and tested fully.
If it was that serious, then you'd have additional checks in place better than a proposed safety net to catch sloppy devs.
即使这个 switch 语句是生死攸关的场景,真正严肃的代码,我也反对在返回后添加“毫无意义”的中断。只要确保编写代码的人都知道他们在做什么,并且代码经过足够多的人并经过全面测试。
如果情况如此严重,那么您将有比提议的安全网更好的额外检查来捕获草率的开发人员。
To argue that break after return adds a safety net, means you're not coding or testing properly. If this is a safety net deemed useful then it's likely there are tons of bugs in the code in potentially more serious places.
争论返回后中断会增加安全网,意味着您没有正确编码或测试。如果这是一个被认为有用的安全网,那么代码中可能存在大量潜在更严重的错误。
The wiki article of "Defensive Programming" was linked to, but it's not relevant here:
“防御性编程”的维基文章被链接到,但这里不相关:
Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software under unforeseen circumstances.
防御性编程是一种防御性设计形式,旨在确保在不可预见的情况下软件的持续功能。
Leaving a safety net breakin is not a scenario of unforeseen circumstances, nor defensive programming. It's just bad coding, and you can't litter your code with back up code just in case you don't code correctly when you change something. That's such a bad approach to coding. The argument that "if someone removed return it won't work", well you could also have a typo in the case var, or forget to write the case, or...
留下安全网break不是不可预见的情况,也不是防御性编程。这只是糟糕的编码,你不能用备份代码乱扔你的代码,以防你在改变某些东西时没有正确编码。这是一种非常糟糕的编码方法。“如果有人删除返回它不起作用”的论点,那么你也可能在 case var 中有错字,或者忘记写 case,或者......
The returnreturns, and you don't code "defensively" to avoid a return failing. That would mean PHP is broken, and you aint gonna fill your code with safety nets to cater for that. That's something you have on a much higher level up.
的return回报,而你没有代码“防守”,以避免一回失败。这意味着 PHP 已损坏,并且您不会用安全网填充您的代码来满足这一点。这是你在更高层次上的东西。
2)breakafter returnkeeps it explicit
2)break在return保持明确之后
But it's explicitly wrong. The returnreturns, so the break won't happen. To me that is scratch head time wondering if I've missed the intent - not for long as it's clear what willhappen, but there will be a moment where I ponder it to make sure I've not missed something.
但这显然是错误的。的return回报,所以破就不会发生。对我来说,这是头疼的时间,想知道我是否错过了意图 - 不是很清楚会发生什么,但会有一段时间我会思考它以确保我没有错过任何东西。
While it's not invalid or error to have a returnand then breakin the same case, it's just entirely pointless as the breakdoes nothing. It's pointless code that needs to be seen, maintained, and figured out as it's not logical.
虽然在同一个 中使用returnand then并不是无效或错误,但它完全没有意义,因为什么都不做。这是无意义的代码,需要查看、维护和弄清楚,因为它不合逻辑。breakcasebreak
If explicitis the core goal andhaving a breakafter a returnurks you because it's pointless, then I'd say it'd be better to set a variable and break, then return the variable after breaking from the switch.
Like @RageZ answer https://stackoverflow.com/a/1437476/2632129
如果显式是核心目标并且有一个breakafter a returnurks 你因为它毫无意义,那么我会说最好设置一个变量 and break,然后在断开开关后返回变量。
像@RageZ 回答https://stackoverflow.com/a/1437476/2632129
3)Set a variable and return after the switch statement is completed
3)设置一个变量,switch语句完成后返回
There's nothing wrong with this approach at all, but if there's no reason to store the value in a variable (later use etc) then it's good to return immediately when there's no need to hang around to do anything else.
这种方法完全没有错,但是如果没有理由将值存储在变量中(以后使用等),那么当不需要做任何其他事情时立即返回是很好的。
That shows clear intent - return a value as soon as the case is matched.
这表明了明确的意图 - 一旦案例匹配就返回一个值。
回答by RageZ
I am not an expert in perfect coding but I think the validator would prefer something like that
我不是完美编码的专家,但我认为验证器更喜欢这样的东西
switch ($foo) {
case 1:
$ret = 1;
break;
case 2:
$ret = 2;
break;
default:
$ret = 3
}
return $ret
I think using return in case statement to break the flow of the code is not really a best practice. So that's why the validator say there is no break ...
我认为使用 return in case 语句来中断代码流并不是真正的最佳实践。所以这就是为什么验证器说没有中断......
For your question about at category, I don't know ... sorry
对于您关于 at 类别的问题,我不知道......抱歉
回答by Sander
From the PHP manual (http://us3.php.net/manual/en/control-structures.switch.php) :
从 PHP 手册(http://us3.php.net/manual/en/control-structures.switch.php):
PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:
PHP 会继续执行语句,直到 switch 块结束,或者第一次看到 break 语句。如果没有在 case 语句列表的末尾写 break 语句,PHP 将继续执行以下 case 的语句。例如:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).
在这里,如果 $i 等于 0,PHP 将执行所有的 echo 语句!如果 $i 等于 1,PHP 将执行最后两个 echo 语句。只有当 $i 等于 2 时,您才会得到预期的行为(将显示“i 等于 2”)。因此,重要的是不要忘记 break 语句(即使在某些情况下您可能希望避免故意提供它们) )。

