Search code examples
phpvariablesdynamicsuperglobals

Use variable variables with superglobal arrays


I wonder if is possible to read dynamically superglobal variables, I would like to do something like that:

<?php

    $n = 'GET';
    $var = '$_'.$n.'[\'something\']'; // pour lire $_GET['something'] 
    echo $var;

//Or 

    $n = 'POST';
    $var = '$_'.$n.'[\'something\']'; // pour lire $_POST['something'] 
    echo $var;

?>

This code don't work as I want, but I would like to know if is workable in PHP?


Solution

  • You can't use variable variables with superglobals, functions or class methods and not with $this.

    And a quote from the manual (It's right before the user comments if you search it):

    Warning: Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.