有没有一种方法来获取变量的名称? PHP-反射 [英] Is there a way to get the name of a variable? PHP - Reflection

查看:104
本文介绍了有没有一种方法来获取变量的名称? PHP-反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这不完全是反思,而是某种. 我想制作一个获取变量并输出var_dump和变量名称的调试函数.

I know this is not exactly reflection, but kind of. I want to make a debug function that gets a variable and prints a var_dump and the variable name.

当然,当程序员编写对函数的调用时,他们已经知道变量的名称,因此他们可以编写如下内容:

Of course, when the programmer writes a call to the function, they already know the variable's name, so they could write something like:

debug( $myvar, 'myvar' );

但是我希望它可以快速,轻松地编写,只需函数名称,变量和变量即可!

But I want it to be quick and easy to write, just the function name, the variable, and voilà !

debug( $myvar ); // quicker and easier :)

推荐答案

您可以通过在将变量传递给函数之前将其转换为键/值集来实现.

You can do it by converting the variable to a key/value set before passing it to the function.

function varName($theVar) {  
   $variableName = key($theVar);  
   $variableValue = $theVar[$variableName];  
   echo ('The name of the variable used in the function call was '.$variableName.'<br />');  
   echo ('The value of the variable used in the function call was '.$variableValue.'<br />');  
}
$myVar = 'abc';
varName(compact('myVar'));

尽管我不建议创建对无名变量的引用,但function varName(&$theVar)也可以.

Though I don't recommend creating a reference to a nameless variable, function varName(&$theVar) works too.

由于compact()将变量名作为字符串而不是实际变量,所以在变量名列表上进行迭代应该很容易.

Since compact() takes the variable name as a string rather than the actual variable, iterating over a list of variable names should be easy.

关于您为什么要这样做-不要问我,但是似乎很多人都在问这个问题,所以这是我的解决方法.

As to why you would want to do this -- don't ask me but it seems like a lot of people ask the question so here's my solution.

这篇关于有没有一种方法来获取变量的名称? PHP-反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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