$literal = "Hello"; $vv = "literal"; echo $$vv; // => prints "Hello"
Are there actually any real use-cases for this language feature?
Assuming a url of
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.
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
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.
It depends on your definition of "good".
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.
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.
As I see them, they:
Even the PHP manual has information which, while unintentional, shows variable variables are complicated and potentially "troublesome":
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.
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.