When to use a variable variable in PHP?

php, variable-variables

Solution

One situation where I've had to use them is URI processing, although this technique might be dated, and I admittedly haven't used it in a long time.

Let's say we want to pull the URI from the script in the format `domain.tld/controller/action/parameter/s`. We could remove the script name using the following:

$uri_string = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['REQUEST_URI']);

To extract the controller, action, and parameter values from this we're going to have to explode the string using the path delimiter '/'. However, if we have leading or trailing delimiters, we'll have empty array values upon explosion, so we should trim those from the beginning and end of the string:

$uri_string = trim($uri_string, '/');

We can now explode the path into an array:

$uri_data = explode('/', $uri_string);

`$uri_data[0]` now contains our controller name, `$uri_data[1]` contains the action name, and values in the array beyond that are parameters that should be passed to the action method.

$controller_name = $uri_data[0];
$action_name = $uri_data[1];

So, now that we have these names, we can use them for a number of things. If you keep your controllers in a very specific directory relative to the site root, you can use this information to `require_once` the controller class. At that point, you can instantiate it and call it using variable variables:

$controller = new $controller_name();
$controller->{$action_name}();    // Or pass parameters if they exist

There are a lot of security gotchas to look out for in this approach, but this is one way I've seen to make use of variable variables.

DISCLAIMER: I'm not suggesting your actually use this code.

Problem

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 good idea ? Or were they included in the language just for fun ?

Original source