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;
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;
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!)