When to use a variable variable in PHP?

后端 未结 8 1736
-上瘾入骨i
-上瘾入骨i 2021-01-03 03:49

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

相关标签:
8条回答
  • 2021-01-03 04:33

    First off, it'd be a huge security concern were you to use user output for these purposes. Internals are the only valid use here.

    Given that, I imagine it's for things like looping through various variables, or sending variables as parameters.

    foreach($name in array('_GET','_POST','_REQUEST')) {
        array_map('stripslashes',$$name);
    }
    
    0 讨论(0)
  • 2021-01-03 04:35

    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.

    0 讨论(0)
提交回复
热议问题