You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不使用条件语句根据变量值实例化特定类对象

替代Switch/If-Else的实例创建方案

直接用关联数组映射表就能实现,把不同type对应的实例创建逻辑绑定到数组键上,直接通过键名调用执行,完全不需要条件判断语句:

// 定义创建逻辑映射表
$creators = [
    'bed' => function($customer, $price, $dimensions) {
        return new Bed($customer, $price, $dimensions);
    },
    'desk' => function($customer, $price, $dimensions) {
        return new Desk($customer, $price, $dimensions);
    },
    'chair' => function($customer, $price, $dimensions, $type) {
        return new Chair($customer, $price, $dimensions, $type);
    }
];

// 调用对应逻辑创建实例(确保$type是映射表中存在的键)
$instance = $creators[$type]($customer, $price, $dimensions, $type);

补充说明

  • 如果需要处理$type不在映射表中的情况,可以加个简单的存在性检查避免报错:
// 兜底返回null
$instance = isset($creators[$type]) ? $creators[$type]($customer, $price, $dimensions, $type) : null;

// 或者抛出异常提示非法类型
if (!isset($creators[$type])) {
    throw new InvalidArgumentException("Unsupported type: {$type}");
}
$instance = $creators[$type]($customer, $price, $dimensions, $type);
  • 这种方式比条件判断更易维护,新增类型时只需要在映射表里追加一行即可,逻辑清晰直观。

内容的提问来源于stack exchange,提问作者Brian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:05:34