PHP数字大小写与goto

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

PHP numeric casing with goto

问题

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

    case 222: return "A"; break;
    case 231: return "B"; break;
    case 234: goto 231;
    case 237: return "C"; break;
    case 251: goto 231;
    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:

    case 222: return "A"; break;
	case 231: return "B"; break;
	case 234: goto 231;
	case 237: return "C"; break;
	case 251: goto 231;
	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”以使用这些新标签)来解决该问题:


function foo($value) {
    switch ($value) {
        case 222:
            return "A";
        case 231:
            label231: // 在这里添加新标签
            return "B";
        case 234:
           goto label231;
        case 237:
           return "C";
        case 251: 
           goto label231;
        case 285:
           return "D";
    }
}

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):

<?php

function foo($value) {
    switch ($value) {
        case 222:
            return "A";
        case 231:
            label231: // new label here
            return "B";
        case 234:
           goto label231;
        case 237:
           return "C";
        case 251: 
           goto label231;
        case 285:
           return "D";
    }
}

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:

确定