0

Possible Duplicate:
what's an actual use of variable variables?

Is there any case in which PHP's variable variables make a solution clearer?

E.g. this:

$a = 'hello';
$$a = 'hello, world!';

echo $hello;
Community
  • 1
  • 1
Joe D
  • 2,855
  • 2
  • 31
  • 25
  • http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/ – philfreo Nov 03 '10 at 17:23
  • 6
    possible duplicate of [a duplicate](http://stackoverflow.com/questions/3582043/variable-variables-when-useful-closed) of a [duplicate](http://stackoverflow.com/questions/3523670/whats-an-actual-use-of-variable-variables) with some more [duplicates](http://stackoverflow.com/questions/1003605/when-to-use-a-variable-variable-in-php) besides. – user229044 Nov 03 '10 at 17:27
  • @meagar Duplicates and duplicate, side by each? – Rudu Nov 03 '10 at 17:34

1 Answers1

1

My example is not exactly over variable variables, but it is similar in intent, as it involves accessing class constants out of a variable containing an instance of the class for the purpose of clarity.

When you are not using namespacing, eventually class names get to be pretty long. I was writing some code this week that needed to do some switch statements to determine the message to write back from a result from a legacy system, but I did not want to compare the result code directly, so I put the code as a constant on the class.

Imagine this with seven more cases.

switch ($resultFromReset) {
        case Application_Users_Results_PasswordResetResult::NEW_PASSWORD_CHANGED_AND_EMAIL_SENT:
            $resultMessage = 'Please check your e-mail for instructions';
            break;

The class name is so long, when I went to put it as a case, it looked huge, ugly and hard to read.

So, to make it easy on myself, I saved a new class into a variable, and referenced the constants from that.

$ResultCode = new Application_Users_Results_PasswordResetResult();

    switch ($resultFromReset) {
        case $ResultCode::NEW_PASSWORD_CHANGED_AND_EMAIL_SENT:
            $resultMessage = 'Please check your e-mail for instructions';
            break;

The variable here neatens the code to make it far more legible.

I could have taken it a step closer to your example with:

$ResultCode = "Application_Users_Results_PasswordResetResult";

    switch ($resultFromReset) {
        case $ResultCode::NEW_PASSWORD_CHANGED_AND_EMAIL_SENT:
            $resultMessage = 'Please check your e-mail for instructions';
            break;

But I did not want to make life difficult for the next poor soul who had to rename my constant!

So, while not exactly the same thing, this gives you a real life example of a few possible uses for variable variables.

(But personally, I would say, steer clear!)

Steve
  • 1,596
  • 1
  • 10
  • 21