PHP动态访问变量值 [英] PHP dynamically accessing variable value

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

问题描述

我想动态访问变量的值,假设我有这个数组:

I want to dynamically access value of variable, let's say I have this array:

$aData = array(
  'test' => 123
);

打印 test key 值的标准方法是:

Standard approach to print the test key value would be:

print $aData['test'];

但是,如果我必须使用变量的字符串表示(出于动态目的)

However, if I have to work with string representation of variable (for dynamic purposes)

$sItem = '$aData[\'test\']';

如何实现打印名为testaData key?下面提供的示例均无效

how can I achieve to print aData key named test? Neither of examples provided below works

print $$sItem;
print eval($sItem);

解决方案是什么?

推荐答案

您的 eval 示例缺少返回值:

Your eval example is lacking the return value:

print eval("return $sItem;");

应该这样做:

$aData['test'] = 'foo';

$sItem = '$aData[\'test\']';

print eval("return $sItem;"); # foo

但是不建议正常使用eval.你可以带着它进入地狱的厨房,因为 eval 是邪恶的.

But it's not recommended to use eval normally. You can go into hell's kitchen with it because eval is evil.

相反,只需解析字符串并返回值:

Instead just parse the string and return the value:

$aData['test'] = 'foo';

$sItem = '$aData[\'test\']';

$r = sscanf($sItem, '$%[a-zA-Z][\'%[a-zA-Z]\']', $vName, $vKey);
if ($r === 2)
{
    $result = ${$vName}[$vKey];
}
else
{
    $result = NULL;
}

print $result; # foo

这也可以通过一些其他形式的正则表达式来完成.

This can be done with some other form of regular expression as well.

由于您的语法与 PHP 非常接近,实际上是它的一个子集,如果您想在使用 eval 之前验证输入,您可以做一些替代.该方法是检查 PHP 令牌并且只允许一个子集.这不会验证字符串(例如语法以及是否实际设置了变量),但会使其更加严格:

As your syntax is very close to PHP an actually a subset of it, there is some alternative you can do if you want to validate the input before using eval. The method is to check against PHP tokens and only allow a subset. This does not validate the string (e.g. syntax and if a variable is actually set) but makes it more strict:

function validate_tokens($str, array $valid)
{
    $vchk = array_flip($valid);
    $tokens = token_get_all(sprintf('<?php %s', $str));
    array_shift($tokens);
    foreach($tokens as $token)
        if (!isset($vchk[$token])) return false;
    return true;
}

您只需为该函数提供一组有效标记.这些是 PHP 令牌,在您的情况下是:

You just give an array of valid tokens to that function. Those are the PHP tokens, in your case those are:

T_LNUMBER (305) (probably)
T_VARIABLE (309)
T_CONSTANT_ENCAPSED_STRING (315)

然后你就可以使用它,它也适用于更复杂的键:

You then just can use it and it works with more complicated keys as well:

$aData['test'] = 'foo';
$aData['te\\\'[]st']['more'] = 'bar';

$sItem = '$aData[\'test\']';
$vValue = NULL;
if (validate_tokens($sItem, array(309, 315, '[', ']')))
{
    $vValue = eval("return $sItem;");
}

我在问题的另一个答案中使用了这个可靠地将包含 PHP 数组信息的字符串转换为数组.

I used this in another answer of the question reliably convert string containing PHP array info to array.

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

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