您显示的条件可以通过位掩码很好地建模:
$messages = [
16 => 'No Visa Required',
8 => 'Visa can be obtained ...',
4 => ...
];
然后,您只需将单独的变量格式化为位掩码:
$bitmask = ($no_required ? 16 : 0)
| ($on_arrival ? 8 : 0)
| ...;
然后只需选择正确的消息:
echo $messages[$bitmask];
注意:这里也必须使用常量而不是幻数,所以它看起来像这样:
define('VISA_NONE', 1);
define('VISA_ON_ARRIVAL', 2);
...
$messages = [
VISA_NONE => 'No Visa Required',
...,
VISA_US | VISA_UK => 'You need USA/UK visa'
];
// using multiplication instead of conditionals, as mentioned in the comments
$bitmask = $no_required * VISA_NONE
| $on_arrival * VISA_ON_ARRIVAL
| ...;
echo $messages[$bitmask];
将整个事情包装在一个适当的类中,你就拥有了一个很好的、可读的、可维护的、可重用的业务逻辑:
class Visa {
const NONE = 1;
const ON_ARRIVAL = 2;
...
protected $messages = [];
protected $visa;
public function __construct() {
$this->messages = [
static::NONE => 'No Visa Required',
...,
static::US | static::UK => 'You need USA/UK visa'
];
}
/**
* @param int $type One of the class constants.
* @param bool $enabled Whether this type of visa is required.
*/
public function set($type, $enabled) {
$this->visa = $this->visa | $type * (int)(bool)$enabled;
}
public function getMessage() {
return $this->messages[$this->visa];
}
}
$visa = new Visa;
$visa->set($visa::NONE, $no_required);
$visa->set($visa::ON_ARRIVAL, $on_arrival);
echo $visa->getMessage();