我知道标题不是很清楚所以这里是代码:
function output($selector){
$one = 1;
$two = 2;
$there = 3;
return ? //should return 1 without if or switch statement
}
echo output('one');
如果可以,怎么做?
答案 0 :(得分:1)
答案 1 :(得分:1)
我个人不喜欢使用变量变量的想法。
为什么不使用数组?
function output($selector){
$choices = array(
'one' => 1,
'two' => 2,
'there' => 3,
);
return $choices[$selector];
}
或者如果您的价值观不是一成不变的话:
function output($selector){
// Complex calculations here
$one = 1;
$two = 2;
$there = 3;
return array(
'one' => $one,
'two' => $two,
'there' => $there,
)[$selector];
}
(是的,我意识到这与使用switch语句非常相似)
答案 2 :(得分:0)
function output($selector){
$one = 1;
$two = 2;
$there = 3;
return $$selector;
}
echo output('one');
但这不是最聪明的事。