简体   繁体   English

在PHP中使用变量NAME作为值

[英]Use variable NAME as value in PHP

Not sure how to ask this without rambling about preprocessors in C, but I will try: 不知道如何询问这个问题而不用担心C中的预处理程序,但是我会尝试:

Is there a way in PHP, to use the name of a variable as a string or value. 有没有在PHP的方式,用一个变量作为一个字符串或值的名称

Such that instead of calling function like this, 这样,而不是像这样调用函数,

$somevar = 'whatever';

fun('somevar', $somevar);

you can call it like this: 您可以这样称呼它:

fun(<magic:$somevar>, $somevar);

or even, dare I say it, like this : 甚至,我敢说, 像这样

fun($somevar);

and the fun() would itself deduce both the value ('whatever'), and the name ('somevar') of the variable. 并且fun()本身会推断出变量的值(“无论如何”)和名称(“ somevar”)。 (In C, it could be done with a preprocessor #define.) (在C语言中,可以使用#define预处理器来完成。)

"magic" above is of course a place holder for the magic syntax in PHP I am looking for which will help me do this. 上面的“ magic”当然是我正在寻找的PHP中magic语法的占位符,它将帮助我做到这一点。 I guess it could be made somehow with eval()? 我猜可以用eval()以某种方式实现? But people keep telling me not to use eval. 但是人们总是告诉我不要使用eval。

Someone hinted that introspection might somehow do the trick. 有人暗示内省也许可以解决问题。 Any leads there would be welcome. 任何线索都将受到欢迎。

Try this 尝试这个

function var_name(&$var, $scope=0)
{
    $old = $var;
    if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;  
}

http://php.net/manual/en/language.variables.variable.php http://php.net/manual/en/language.variables.variable.php

The probably explain it better than I can, I think this is what you're looking for? 可能比我能更好地解释它,我认为这是您想要的?

Alright, before you call the function do the following: 好吧,在调用该函数之前,请执行以下操作:

$var= "variableName";
$$var = "variableValue";
fun($var);

Now within the function definition for fun: 现在,在函数定义中查找乐趣:

function fun($parameter)
{
    global $$parameter;
    echo $parameter; //echos the variableName
    echo $$parameter; //echos the variableValue
}

No. PHP's scoping rules prevent you from doing that. 不会。PHP的范围规则禁止您这样做。 The only way would be through a pre processor (as you are aware) or by introspecting the code, which would be kind of the same thing. 唯一的方法是通过预处理器(如您所知)或通过对代码进行自省,这有点相同。 PHP has a built-in tokenizer, that you can use to parse a file with. PHP具有内置的令牌生成器,可用于与之一起解析文件。 You can use debug_backtrace to find out which files to parse through. 您可以使用debug_backtrace找出要解析的文件。 It's going to be a really messy and inefficient thing to do though, so you would probably be better off rethinking what you're doing. 这将是一件非常麻烦且效率低的事情,因此重新考虑自己的工作可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM