简体   繁体   English

带有 goto 的 PHP 数字大小写

[英]PHP numeric casing with goto

I pleasantly found that it is possible to use goto in PHP:我愉快地发现可以在 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;

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.有很多键共享相同的值,所以我尝试使用 goto 来消除冗余。 I'm use a switch since it's simpler here than if/else branching.我使用的是 switch,因为它比 if/else 分支更简单。

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但是,通过验证器运行它,我得到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?我在这里缺少什么语法?

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):标签不能仅为数字,因此您只能通过为要定位的cases创建额外标签来解决它(并使用这些新标签修改gotos ):

<?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.).但是,正如评论中提到的,我更愿意选择不同的方法(关联数组等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM