【问题标题】:Is there a shorthand for conditional assigning in PHPPHP中有条件分配的简写吗
【发布时间】:2017-11-29 19:43:14
【问题描述】:

我有以下(简化的)代码片段,我想根据特定条件为变量 $shell 或 $hole 赋值($ringIndex===1)

foreach($rings as $ringIndex=>$ring) {
    $polygon = $this->getPolygonFromRing($ring);
    if($ringIndex===1) {
        $shell = $polygon;
    } else {
        $hole = $polygon;
    }
    .... 
}

如果没有必要,我不想使用额外的变量 ($polygon)

我想也许这样的事情会起作用:

foreach($rings as $ringIndex=>$ring) {
    ($ringIndex===1?$shell:$hole) = $this>getPolygonFromRing($ring);
    ...
}

【问题讨论】:

    标签: php conditional assign


    【解决方案1】:

    你可以使用变量变量。

    foreach($rings as $ringIndex=>$ring) {
        ${$ringIndex===1?'shell':'hole'} = $this->getPolygonFromRing($ring);
        .... 
    }
    

    但是,我将添加我的一般建议:任何时候您发现自己需要可变变量时,您几乎总是应该使用数组来代替。如果变量类似于$foo1$foo2 等,那么它应该是一个索引数组,但在您的情况下,它可能应该是一个带有键 shellhole 的关联数组。

    【讨论】:

    • 我觉得我的很淘气。
    • 我最初想出了你的,然后意识到它可以这样组合。
    • 绝妙(但有潜在危险)的捷径,也是编辑中的好建议。
    【解决方案2】:
    foreach($rings as $ringIndex => $ring){
        $var = $ringIndex === 1 ? 'shell' : 'hole';
        $$var = $this->getPolygonFromRing($ring);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多