是否可以使用 ||在 PHP 中切换?
switch ($foo)
{
case 3 || 5:
bar();
break;
case 2:
apple();
break;
}
上面的代码中,第一个 switch 语句是否有效?如果 $foo
的值为 3 或 5,我希望它调用函数 bar()
switch ($foo)
{
case 3 || 5:
bar();
break;
case 2:
apple();
break;
}
In the above code, is the first switch statement valid? I want it to call the function bar()
if the value of $foo
is either 3 or 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该利用 switch 语句的失败:
PHP 手册页 有一些这样的例子。
You should take advantage of the fall through of switch statements:
The PHP man page has some examples just like this.
我认为你需要的是:
有趣的是,我听说 Perl 正在(或者甚至现在)引入了这种语法,大致如下:
我不是一个大粉丝因为我必须编写大量词法解析器,并且相信语言应该尽可能明确,所以我使用了该语法。但是,Perl 之前已经用那些可怕的尾部
if
和or
解决了所有这些问题,所以我怀疑它不会有任何问题:- )I think what you need is:
Interestingly, I've heard that Perl is (or maybe even has, by now) introducing this syntax, something along the lines of:
I'm not a big fan of that syntax since I've had to write lexical parsers quite a bit and believe languages should be as unambiguous as possible. But then, Perl has solved all these sorts of problems before with those hideous tail-side
if
s andor
s so I suspect there'll be no trouble with it :-)相反,请使用 switch 语句的主要优点之一:
Instead, use one of the primary advantages of
switch
statements:是的,我认为你所拥有的相当于:
Yeah, I think what you've got there is equivalent to:
不,如果你写了
case 3 || 5:
,那么你还不如直接写case True:
,这肯定不是你想要的。但是,您可以将 case 语句直接放在彼此下面:No, if you wrote
case 3 || 5:
, then you might as well just writecase True:
, which is certainly not what you wanted. You can however put case statements directly underneath each other: