The following is an example following the syntax of a variable name, which also resolves array elements:
// 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"]);
With the following implementation:
$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; }; };
Since you cannot overload variables in PHP, you are limited to expressing PHP here, that is, there is no write context for variable references as function return values, which requires additional smoothing:
$var = &$vars($string);
If something like this does not fit your needs, you need to fix PHP, and if not an option, PHP does not offer the language features you are looking for.
See also a related question: use strings to access (potentially large) multidimensional arrays .
hakre source share