多条件 switch 语句?

发布于 2024-12-06 13:40:26 字数 252 浏览 0 评论 0原文

这是我在 switch() 的 PHPdoc 中没有看到的东西,所以我不确定它是否可能,但我想要一个多条件的情况,例如:

switch($this) {
   case "yes" || "maybe":
      include "filename.php";
      break;
   ... 
}

这是有效的语法/是否可以通过 switch() 语句实现?

This is something that I haven't seen in the PHPdoc for switch() so I'm not sure if it's possible, but I'd like to have a case which is multi-conditional, such as:

switch($this) {
   case "yes" || "maybe":
      include "filename.php";
      break;
   ... 
}

Is this valid syntax/is this even possible with a switch() statement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

远昼 2024-12-13 13:40:26

通常你只会用例失败。

switch($this) {
   case "yes":
   case "maybe":
      include "filename.php";
      break;
   ... 
}

Usually you'd just use case fall-through.

switch($this) {
   case "yes":
   case "maybe":
      include "filename.php";
      break;
   ... 
}
半山落雨半山空 2024-12-13 13:40:26

这是有效的语法/这甚至可以通过 switch() 语句实现吗?

不,不。该表达式将被计算为 ("yes" or "maybe"),结果为 true。然后 switch 将针对该结果进行测试。

你想使用

case "yes":
case "maybe":
// some code
break;

Is this valid syntax/is this even possible with a switch() statement?

No and no. The expression will be evaluated as ("yes" or "maybe"), which will result in true. switch will then test against that result.

You want to use

case "yes":
case "maybe":
// some code
break;
情独悲 2024-12-13 13:40:26

应该是

switch($this) { 
   case "yes":
   case "maybe": 
      include "filename.php"; 
      break; 
   ...  
} 

Should be

switch($this) { 
   case "yes":
   case "maybe": 
      include "filename.php"; 
      break; 
   ...  
} 
梦过后 2024-12-13 13:40:26

您可以通过失败来做到这一点:

switch ($this) {
    case "yes":
    case "no":
        include "filename.php";
        break;
}

You can do this with fall-through:

switch ($this) {
    case "yes":
    case "no":
        include "filename.php";
        break;
}
半窗疏影 2024-12-13 13:40:26

当然,只需指定两种情况而不破坏第一个情况,如下所示:

switch($this) {
   case "yes":
   case "maybe":
      include "filename.php";
      break;
   ... 
}

如果不破坏一种情况,则该情况的任何代码都会运行,并继续执行其他代码,直到执行被破坏。它将继续遍历其下面的所有情况,直到看到中断

Sure, just specify two cases without breaking the first one, like so:

switch($this) {
   case "yes":
   case "maybe":
      include "filename.php";
      break;
   ... 
}

If you don't break a case, then any code for that case is run and continues on to execute additional code until the execution is broken. It will continue through all cases below it until it sees a break.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文