我想问你在两个相似的解决方案中选择哪个。
第一种方式:
public function test($myvar) {
switch ($myvar) {
case 'test1': return [
'value' => 'Value of test1',
'short' => 'Val 1'
];
break;
}
}
$this->test('test1')['short'] // Val 1
第二种方式:
public function test($myvar, $key) {
switch ($myvar) {
case 'test1': $array = [
'value' => 'Value of test1',
'short' => 'Val 1'
];
}
return $array[$key];
}
$this->test('test1', 'short') // Val 1
即使两个函数返回相同的值,对你们来说最优雅和可读的方法是什么?
对我来说是第二个几乎没有修改的。看一下:
public function test($myvar, $key = null) {
switch ($myvar) {
case 'test1': $array = [
'value' => 'Value of test1',
'short' => 'Val 1'
];
}
if(!empty($key))
return $array[$key];
else
return $array;
}
使用:
$this->test('test1', 'short') // Val 1
$this->test('test1')['short'] // Val 1
$this->test('test1')['value'] // Value of test1
这样你就可以在一个函数中使用这两个方法。请记住,函数需要尽可能泛型,以便代码更少,功能更多。"代码不是资产,而是负债。你写得越多,以后需要维护的内容就越多。":)