直接从string创建对变量的引用(不带switch语句)

时间:2011-05-21 23:07:45

标签: php

我知道标题不是很清楚所以这里是代码:

function output($selector){
    $one = 1;
    $two = 2;
    $there = 3;

    return ? //should return 1 without if or switch statement
}


echo output('one');

如果可以,怎么做?

3 个答案:

答案 0 :(得分:1)

使用variable variable前缀$selector变量前加$

return $$selector;

请记住进行健全性检查和/或实现默认值,这样就不会在函数中产生不必要的未定义变量错误等。

答案 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');

但这不是最聪明的事。