Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Today I encountered this little PHP gem called variable variables.

$literal = "Hello";
$vv = "literal";
echo $$vv; // => prints "Hello"

Are there actually any real use-cases for this language feature?

share|improve this question
1  
Like most "obscure tricks" its actual use cases are very limited, there are usually much cleaner ways to implement those use cases and even if the use case matches the trick perfectly, it will be hard to maintain. –  Joachim Sauer Jun 28 '12 at 10:24
1  
@JoachimSauer It's not really obscure, variable variables are at the heart of foreach loops. –  Yannis Jun 28 '12 at 10:31

3 Answers 3

up vote 14 down vote accepted

Assuming a url of http://example.com/hello/world, and the following .htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ router.php?/$1 [L]

router.php, an overly simplistic router, would be:

<?php

$request = explode("/", $_SERVER["REQUEST_URI"]);

$controllerClass = $request[0];
$controllerActionMethod = $request[1];

$controller = new $controllerClass();
$controller->$controllerActionMethod(); // hello::world();

?>

That's a pretty standard practical use of variable variables. Neat trick, but you should be extremely careful when using it, over/abusing it will certainly lead to horribly unmaintainable code.

Disclaimer: The code presented in the answer is only intended to illustrate the use of the feature. It does not cover proper design, security, maintainability, or sanity. Do not use.

share|improve this answer
8  
Disclaimer: The code presented in the answer is only intended to illustrate the use of the feature, nothing else. Quality wise it's absolutely crap, do not use. –  Yannis Jun 28 '12 at 1:34
    
(PHP newbie here) I don't see where exactly you used the variable variables, I only see single dollars. I suspect it's got to do with the .htaccess, but I don't understand those well, either. –  Manishearth Jun 28 '12 at 10:25
3  
@YannisRizos - Your example is using a variable method name, not a variable variable. It's entirely different. You are effectivly calling a method via reflection rather than a variable by reflection. –  Jonno Jun 28 '12 at 11:31
1  
@Jonno Heh, I thought exactly the same when somebody first explained variable variables to me ;) The first "variable", however, refers to the dynamic nature of the (second) variable (the structure), and its method is referenced dynamically, and that's about it. $controller is a variable (the structure), but what it holds is set dynamically, thus a variable variable. Bit of a silly name, ain't it? –  Yannis Jun 28 '12 at 11:41
1  
@YannisRizos - I would respectfully disagree. A variable variable, is exactly that a variable, which is created at the scope of the currectly created code. What you are doing here is calling a method, who's name is defined by a variable. By that logic, any use of a 'variable' to do anything that... 'varies' is a variable variable. –  Jonno Jun 28 '12 at 13:17

Are there any good use-cases for variable variables?

It depends on your definition of "good".
My personal answer is simply no.

I tried to come up with one just to answer this question, I raked help questions on SO where people are using them, and read a guides and blog posts.

I just cannot find a scenario where it can be argued using a variable variable is more useful or worthwhile than another approach.

All I could think of and found where reasons against their usage.

I even read one article, with grateful and positive comments, which argued how it can make switch statements easier.
Switch statements, "simpler"?


I'd argue that even to someone very new to PHP, an array might arguably be a little trickier to wrap their head around at first, but the learning curve would drop way past that of learning variable variables once they begin trying to use them within code.

It would soon become confusing trying to follow and control the flow of variable variables.
Whereas once learned, an array is quite simple to look at and use.


As I see them, they:

  • Never resolve any problem which another option is not at least equally suited, usually better
  • Make managing the codebase harder, because rather than a separate variable with separate data, you now have "linked" variables tightly coupled together, which is a mess waiting to happen
  • Are very rarely used, so readability is arguably lowered due to unfamiliarity. Especially in classes/methods where missing that extra $ ($var->*$*rogueVar) will be a temporary pain
  • The information for the child variable is not available without the parent. $var = "james"; var name and value are right there.
  • Even the summary sounds icky - "a variable named based on a value from another variable"

Even the PHP manual has information which, while unintentional, shows variable variables are complicated and potentially "troublesome":

PHP.net wrote:

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

As their usage is very uncommon, I would argue that even seasoned developers would suddenly have some learning curve if another dev used this in their code.

Variable variables cannot be used with PHP's Superglobal arrays within functions or class methods.
This is more learning, and careful consideration to work around problems which using variable variables introduce.

For no benefit.


I think they may have been quite useful in older times, when "dinosaurs" roamed the datacentres. and PHP had not been refactored greatly and so much faster with things such as arrays etc.


If variable variables gave us some profound functionality, or even just highly useful, then perhaps using them would be worth the learning.

However, given what they offer, I just do not see the point in ever using them, even if an array is overkill and used some microseconds more, for the sake of code maintainability, readability, sanity preservation, and no difference in functionality, just use an alternative method - every time.

share|improve this answer

Honestly? In nearly 10 years of PHP experience I've never encountered a problem to which the only solution (or indeed the best solution from a choice) was to use a variable variable. The closest I've got is being able to access constants on an instance of a class such as $classInstance::CLASS_CONSTANT (which has been available since PHP 5.3) and even then I don't normally have much use for it.

I suspect it's one of the many warts that exist in PHP that seemed like a good idea at the time.

So in answer to your question, if there are use cases where it's the best or only approach to a particular problem, I've not seen them.

share|improve this answer
    
Same here - in seven years I worked on and off with PHP I never encountered vv (in production code anyway). –  miku Jun 28 '12 at 13:28
    
Variable variables may seem like a neat trick, but then it will bite you (or someone else) horribly later on when they try to upgrade/maintain the code. Variable variables combined with global scope result in disaster where simply renaming a variable could make your code fall over. It also means that your code cannot be improved by the JIT compiler in HHVM should that ever be an issue. –  Programster Jun 12 '14 at 14:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.