I\'ve been developing in PHP for a while now, and I still have not had a task where I\'ve had to use variable variables. Can anyone give me examples where using them is a go
I haven't found many uses for variable variables but using variables for methods can be handy, as long as what you're doing is clear. For example in a simple REST service you might do something like this:
$method = $request->getMethod(); // 'post','get','put','delete'
try
{
$response = $resource->$method($request->getInput());
}
catch (BadMethodException $badMethod)
{
$response = $responseFactory->getError($badMethod);
}
Some would argue you could do this equally well with a switch
statement (which you could) but this way lends itself to extensibility (if you decide to add another method type) and maintains the abstraction of applying a method on a resource.
Unless you are working with multi-depth variables (which you won't need to if you are not doing anything fancy) you will probably don't need them. Even then, you can probably find another way to write down the same thing and still get the same result. It can be shorter (and in some cases even easier to understand) to use them though, so I for one am glad that it is part of the language.
I've found a quite good one..
$php = "templates/php/default.php";
$html = "templates/html/default.php";
$css = "templates/css/default.php";
$js = "templates/js/default.php";
now i asked the user to say which file he wants php or/and html..
$userarray = array("php", "css");
foreach($userarray as $file){
var_dump($$file);
}
output:
templates/php/default.php
templates/css/default.php
I've crossed myself with this when trying to scope static variables
self::$file;
like this then I remembered I could use variable variables
self::$$file;
which will be interpreted as self::$php;
It's not uncommon for languages to include features you shouldn't touch with a bargepole (I even asked a question about it a while back), and variable variables are probably one of those constructs that fall into this category. Just because a language contains a feature doesn't mean to say you have to use it.
There may be occasions when they solve a problem (after all recursion is rarely used in practice but no-one would argue that's not an essential construct) but in general any language feature that obscures what your code is doing, and variable variables defiantly fall into this category, should be treated with extreme caution.
Never use them; an "array" is always a better solution.
I generally find them in places where the code smells bad. Maybe references a static configuration variable etc... But why wouldn't the usual associative array have been a better solution. Seems like a security hole waiting to happen.
I suppose you might be able to use them in templates effectively.