首页 > 解决方案 > 开关改进

问题描述

我有以下开关盒,但目前包含 10 个条件。

public function convertParameters(string $key, $value)
{
    switch ($key) {
        case "office":
        case "name":
        case "first_name":
        case "last_name":
            $value = ucfirst($value);
            break;
        case "email":
            $value = strtolower($value);
            break;
        case "street":
        case "city":
            $value = ucwords($value);
            break;
        case "start":
        case "end":
            $value = \DateTime::createFromFormat("Y-m-d H:i:s", $value);
            break;
    }
    return $value;
}

有谁知道我可以如何改进此功能以减少条件?(或其他改进)

标签: phpswitch-statement

解决方案


您的方法看起来不错,但如果您正在寻找替代方法,您可以使用从键​​映射到函数的数组。

$ops = [
    "office" => "ucfirst",
    "name" => "ucfirst",
    "first_name" => "ucfirst",
    "last_name" => "ucfirst",
    "email" => "strtolower",
    "street" => "ucwords",
    "city" => "ucwords",
    "start" => function($d) { return DateTime::createFromFormat("Y-m-d H:i:s", $d); },
    "end" => function($d) { return DateTime::createFromFormat("Y-m-d H:i:s", $d); }
];

if (isset($ops[$key])) {
    return $ops[$key]($value);
} else {
    return $value;
}

推荐阅读