1

I know the title is not very clear so here it's in code:

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

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


echo output('one');

If this is possible, how?

0

3 Answers 3

1

Use a variable variable by prefixing the $selector variable with another $:

return $$selector;

Remember to do sanity checks and/or implement default values, so you don't end up generating unnecessary undefined variable errors and such from within your function.

Sign up to request clarification or add additional context in comments.

2 Comments

I was just going to try that but my code editor (notepad++) led me to believe that it would not be right. :)
@Chad: I know what you mean, but don't worry, it's just a bug with Notepad++'s syntax highlighting.
1

I personally don't like the idea of using variable variables.

Why not just use an array?

function output($selector){
    $choices = array(
        'one' => 1,
        'two' => 2,
        'there' => 3,
    );

    return $choices[$selector];
}

or if your values aren't set in stone:

function output($selector){
    // Complex calculations here
    $one = 1;
    $two = 2;
    $there = 3;

    return array(
        'one' => $one,
        'two' => $two,
        'there' => $there,
    )[$selector];
}

(Yes, I realize this is pretty similar to using a switch statement)

Comments

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

    return $$selector;
}


echo output('one');

But it's not most clever thing.

2 Comments

"not most clever thing" can you explain why please?
BoltClock answered more detailed. In addition: IDE will not be able to suggest code completion in this case - typos, errors. Or in variable can be some kind of users input and it will be security issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.