带数组键的PHP变量变量 [英] PHP Variable Variables with array key

查看:150
本文介绍了带数组键的PHP变量变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道是否有解决方法(或者是否有可能).

Just wondering if there is a way around this (or if it is even possible).

因此,我有一段类似于此的代码.我有一个字符串,其值包含方括号,类似于访问数组键时使用的字符串.我想通过使用字符串值本身创建该数组键.我希望这段代码能更好地理解我的意思.

So I have a section of code similar to this. I have a string, with a value that contains square brackets, similar to those used when accessing an array key. I want to create that array key itself by using the strings value. I hope this code makes a little more sense of what I mean.

// 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'.

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

Can't seem to get it to work correctly, however. Is it possible (or how else can I go about it)?

推荐答案

下面是变量名语法也可以解析数组成员的示例:

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"

具有以下实现方式:

/**
 * @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;
    };
};

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

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);

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

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.

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

这篇关于带数组键的PHP变量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆