PHP数字大小写与goto

huangapple go评论97阅读模式
英文:

PHP numeric casing with goto

问题

我愉快地发现在PHP中可以使用goto

  1. case 222: return "A"; break;
  2. case 231: return "B"; break;
  3. case 234: goto 231;
  4. case 237: return "C"; break;
  5. case 251: goto 231;
  6. case 285: return "D"; break;

我有一些类似这样的代码。有很多键共享相同的值,所以我试图使用goto来消除冗余。我在这里使用switch,因为它比if/else分支更简单。

出于各种原因,每种情况都必须像上面一样明确定义,即使它只是转到另一个情况。然而,将此通过验证器运行时,我收到Parse error: syntax error, unexpected '231' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) in your code错误消息。

我尝试将情况用单引号括起来,但仍然无法通过。这似乎与上面的示例一致。在语法方面我漏掉了什么?

英文:

I pleasantly found that it is possible to use goto in PHP:

  1. case 222: return "A"; break;
  2. case 231: return "B"; break;
  3. case 234: goto 231;
  4. case 237: return "C"; break;
  5. case 251: goto 231;
  6. case 285: return "D"; break;

I have some code like this. There are a lot of keys that shared the same value, so I am trying to use goto to eliminate redundancy. I'm use a switch since it's simpler here than if/else branching.

For various reasons, each case must be explicitly defined as above, even if it just goes to another case. However, running this through a validator, I get Parse error: syntax error, unexpected ''231'' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) in your code

I tried surrounding the cases with single quotes, but that still didn't pass. This seems in line with the example above. What am I missing syntax-wise here?

答案1

得分: 1

标签不能仅为数字,所以您只能通过为要定位的“cases”创建额外的标签(并修改“gotos”以使用这些新标签)来解决该问题:

  1. function foo($value) {
  2. switch ($value) {
  3. case 222:
  4. return "A";
  5. case 231:
  6. label231: // 在这里添加新标签
  7. return "B";
  8. case 234:
  9. goto label231;
  10. case 237:
  11. return "C";
  12. case 251:
  13. goto label231;
  14. case 285:
  15. return "D";
  16. }
  17. }
  18. var_dump(foo(251));

然而,正如评论中提到的,我更喜欢选择不同的方法(例如关联数组等)。

英文:

Label cannot be numeric only, so you could only solve it by creating extra label for cases you want to target (and also modifying gotos with those new labels):

  1. <?php
  2. function foo($value) {
  3. switch ($value) {
  4. case 222:
  5. return "A";
  6. case 231:
  7. label231: // new label here
  8. return "B";
  9. case 234:
  10. goto label231;
  11. case 237:
  12. return "C";
  13. case 251:
  14. goto label231;
  15. case 285:
  16. return "D";
  17. }
  18. }
  19. var_dump(foo(251));

However as mentioned in the comments, I would prefer choosing a different approach (associative array etc.).

huangapple
  • 本文由 发表于 2020年1月3日 21:00:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579092.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定