带有数组键的PHP变量变量

Mat*_*ddy 6 php

只是想知道是否有办法(或者甚至可能).

所以我有一段与此类似的代码.我有一个字符串,其值包含方括号,类似于访问数组键时使用的字符串.我想通过使用字符串值来创建该数组键.我希望这段代码能够更清楚地表达我的意思.

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

// I could then print the array keys value like this
print( $welcome["hello"] );

// This would hopefully output 'thisworks'.
Run Code Online (Sandbox Code Playgroud)

但是,似乎无法让它正常工作.是否有可能(或者我还能怎么做)?

Shi*_*dim 5

变量变量中字符串处理的字符串中的字符.他们不解释字符串中的内容.因此,[]字符中的字符$string不会被视为数组表示法.而是将其视为变量名称的一部分.

在执行$$string = 'thisworks';PHP之后,创建一个名称welcome["hello"]字面值设置为的变量thisworks.

要打印它,请使用此表示法,

print (${'welcome["hello"]'});
Run Code Online (Sandbox Code Playgroud)


hak*_*kre 5

以下是遵循变量名语法的示例,该语法还解析数组成员:

// 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"
Run Code Online (Sandbox Code Playgroud)

通过以下实现:

/**
 * @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;
    };
};
Run Code Online (Sandbox Code Playgroud)

由于您无法在PHP中重载变量,因此这里只限于PHP的表现力,这意味着变量引用作为函数返回值没有写上下文,这需要其他别名:

$var = &$vars($string);
Run Code Online (Sandbox Code Playgroud)

如果类似这样的事情不符合您的需求,则需要打补丁PHP;如果不是这样,则PHP不会提供您要寻找的语言功能。

还可参见相关问题:使用字符串访问(可能较大的)多维数组