如何在PHP中更容易地将整数值映射到字符串?

时间:2009-04-29 01:29:51

标签: php

如何重新考虑以下代码以使其更简洁,更易于维护?

if ($row['vocation'] == 1) $vocation = "sorcerer";
if ($row['vocation'] == 2) $vocation = "druid";
if ($row['vocation'] == 3) $vocation = "paladin";
if ($row['vocation'] == 4) $vocation = "knight";

if ($row['vocation'] == 5) $vocation = "master sorcerer";
if ($row['vocation'] == 6) $vocation = "elder druid";
if ($row['vocation'] == 7) $vocation = "royal paladin";
if ($row['vocation'] == 8) $vocation = "elite knight";
else $vocation = "none";

6 个答案:

答案 0 :(得分:17)

我建议使用一个数组,如下所示:

static $vocations = array(
  1 => 'sorceror',
  2 => 'druid',
  3 => 'paladin',
  4 => 'knight',
  5 => 'master sorceror',
  6 => 'elder druid',
  7 => 'royal paladin',
  8 => 'elite knight',
  );

$vocation = 
  isset($vocations[$row['vocation']]) ? $vocations[$row['vocation']] : 'none';

答案 1 :(得分:2)

以下是使用开关执行此操作的示例:

switch ($row['vocation']) {
    case 1:
        $vocation = "sorcerer";
        break;
    case 2: 
        $vocation = etc..
    default:
        $vocation = "none";
}

对于许多语言,如C,Java和C#以及许多其他语言,这是很常见的事情。

答案 2 :(得分:1)

以下作品可能会好一些。 8个元素没问题,但如果列表包含1000则该怎么办。

$list = array("sorcerer", "druid", ...);

$vocation = "none";

if($row['vocation'] <= count($list)){
    $vocation = $list[$row['vocation'] - 1];
}

答案 3 :(得分:1)

这是另一个建议:

<?php

class Action
{
    const TYPE__ADD = 0;
    const TYPE__VIEW = 1;
    const TYPE__EDIT = 2;
    const TYPE__PATCH = 3;
    const TYPE__DELETE = 4;
    const TYPE__MAP = [
        self::TYPE__ADD => 'add',
        self::TYPE__VIEW => 'access',
        self::TYPE__EDIT => 'edit',
        self::TYPE__PATCH => 'patch',
        self::TYPE__DELETE => 'delete'
    ];

    protected $type;

    public function setType(int $type)
    {
        if (!isset(self::TYPE__MAP[$this->type])) throw new \Exception(sprintf('Invalid type. Possible options are: %s.', implode(',', self::TYPE__MAP)));

        $this->type = $type;
    }

    public function getType(): int
    {
        return $this->type;
    }

    public function getTypeStr(): string
    {
        return self::TYPE__MAP[$this->type];
    }
}

// Test
$action = new Action();
$action->setType(Action::TYPE__PATCH);
echo 'Action type is: '.$action->getTypeStr().', and its representative int value is: '.$action->getType();

答案 4 :(得分:0)

正确启动你的项目,现在使用const来表示那些数字常量,并为自己省去一些令人头疼的问题。 (除了使用其他人建议的开关/外壳)

答案 5 :(得分:0)

我会使用数组的建议,我会使用常量来表示这样的整数值:

define('VOCATION_SORCEROR', 1);
define('VOCATION_DRUID',    2);
define('VOCATION_PALADIN',  3);

$vocations = array(
  VOCATION_SORCEROR => 'sorceror',
  VOCATION_DRUID =>    'druid',
  VOCATION_PALADIN =>  'paladin'
);