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


Creating a reference to variable directly from string (without switch statement)

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

function output($selector){
    $one = 1;
    $two = 2;
    $there = 3;
    return ? //should return 1 without if or switch statement
}

echo output('one');

如果这是可能的,如何?

通过在$selector变量前面加上另一个$来使用变量变量:

return $$selector;

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

我个人不喜欢使用变量的想法。

为什么不直接使用数组?

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 语句非常相似)

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

echo output('one');

但这不是最聪明的事情。