更好的写作方式如果是其他声明

时间:2015-04-06 13:33:46

标签: php if-statement coding-style

有没有更好的方法来写这个:

if (in_array('WIN_WAITING', $statuses)) {
    $this->globalStatus = 'WIN_WAITING';
} else if (in_array('IN_PLAY', $statuses)) {
    $this->globalStatus = 'IN_PLAY';
} else if (in_array('WON', $statuses)) {
    $this->pay($this->tickets['ticketID']);
    $this->globalStatus = 'WON';
} else if (in_array('PAYEDOUT', $statuses)) {
    $this->globalStatus = 'PAYEDOUT';
} else if (in_array('CLOSED', $statuses)) {
    $this->globalStatus = 'CLOSED';
} else if (in_array('LOST', $statuses)) {
    $this->globalStatus = 'LOST';
} else if (in_array('OPEN', $statuses)) {
    $this->globalStatus = 'OPEN';
}

2 个答案:

答案 0 :(得分:3)

这应该适合你:

(这里我只是遍历你所有的搜索字符串,如果我找到了它,我会打破循环)

<?php

    $search = ["WIN_WAITING", "IN_PLAY", "WON", "PAYEDOUT", "CLOSED", "LOST", "OPEN"];

    foreach($search as $v) {
        if(in_array($v, $statuses)) {
            if($v == "WON") $this->pay($this->tickets['ticketID']);
            $this->globalStatus = $v;
            break;
        }

    }

?>

答案 1 :(得分:2)

也许像

$options = array('WIN_WAITING', 'IN_PLAY', 'WON', 'PAYEDOUT', 'CLOSED', 'LOST', 'OPEN');

for($i=0; $i<=7; $i++) {

 if(in_array($options[$i], $statuses)) {
   $this->globalStatus = $options[$i];
   break;
 }

}

未经测试,只是一个想法