PHP Variable Variables with array key

The following is an example following your variable name syntax that resolves array members as well:

// String that has a value similar to an array key
$string = 'welcome["hello"]';

// initialize variable function (here on global variables store)
$vars = $varFunc($GLOBALS);

// alias variable specified by $string
$var = &$vars($string);

// set the variable
$var = 'World';

// show the variable
var_dump($welcome["hello"]); # string(5) "World"

With the following implementation:

/**
 * @return closure
 */
$varFunc = function (array &$store) {
    return function &($name) use (&$store)
    {
        $keys = preg_split('~("])?(\\["|$)~', $name, -1, PREG_SPLIT_NO_EMPTY);
        $var = &$store;
        foreach($keys as $key)
        {
            if (!is_array($var) || !array_key_exists($key, $var)) {
                $var[$key] = NULL;
            }
            $var = &$var[$key];
        }
        return $var;
    };
};

As you can not overload variables in PHP, you are limited to the expressiveness of PHP here, meaning there is no write context for variable references as function return values, which requires the additional aliasing:

$var = &$vars($string);

If something like this does not suit your needs, you need to patch PHP and if not an option, PHP is not offering the language features you're looking for.

See as well the related question: use strings to access (potentially large) multidimensional arrays.


In Variable variables characters in a string treated literally. They do not interpret whats inside the string. So [] characters in the $string is not treated as array notation. Rather its treated as a part of the variable name.

after you execute $$string = 'thisworks'; PHP creates a variable with name welcome["hello"] literally with value set to thisworks.

To print it use this notation,

print (${'welcome["hello"]'});

Tags:

Php