有没有一种方法来获取变量的名称? PHP

编程入门 行业动态 更新时间:2024-10-22 22:51:18
本文介绍了有没有一种方法来获取变量的名称? 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

本文发布于:2023-05-28 06:54:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/315094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!