今天接手一个项目,多处看到一坨坨case,心想能不能优化一下代码结构。case分支少于5个还好,多了看起来头晕。代码结构如下:
switch ($type){
case 'A':
//doSomething
case 'B':
//doSomething
case 'C':
//doSomething
case 'D':
//doSomething
case 'E':
//doSomething
case 'F':
//doSomething
case 'G':
//doSomething
case 'D':
//doSomething
}
优化一:利用动态函数,先定义case对应的方法。
{
$type='A';
$handlerMap=[
'A'=>'a',
'B'=>'b'
];
if(!isset($handlerMap[$type])){
return 'messageType not found';
}
//return $this->a($type);
return $this->{$handlerMap[$type]}($type);
}
public function a($type){
return json_encode(['a'=>$type]);
}
优化二:call_user_func或者call_user_func_array,先定义case对应的方法。
{
$type='A';
$handlerMap=[
'A'=>'a',
'B'=>'b'
];
if(!isset($handlerMap[$type])){
return 'messageType not found';
}
return call_user_func(array(__CLASS__, $handlerMap[$type]),[$type]);
// return call_user_func_array(array(__CLASS__, $handlerMap[$type]),[$type]);
}