PHP – Good Use-Cases for Variable Variables

code-qualityPHPprogramming-languages

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?

Best Answer

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.

Related Topic