How to get a variable name as a string in PHP?(如何在 PHP 中将变量名作为字符串获取?)
问题描述
假设我有这个 PHP 代码:
Say i have this PHP code:
$FooBar = "a string";
然后我需要这样的函数:
i then need a function like this:
print_var_name($FooBar);
哪个打印:
FooBar
任何想法如何实现这一目标?这在 PHP 中是否可行?
Any Ideas how to achieve this? Is this even possible in PHP?
推荐答案
你可以使用 get_defined_vars() 来查找与您要查找的名称具有相同值的变量的名称.显然这并不总是有效,因为不同的变量通常具有相同的值,但这是我能想到的唯一方法.
You could use get_defined_vars() to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.
get_defined_vars() 似乎无法正常工作,它返回 'var' 因为在函数本身中使用了 $var.$GLOBALS 似乎可以工作,所以我将其更改为.
get_defined_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.
function print_var_name($var) {
foreach($GLOBALS as $var_name => $value) {
if ($value === $var) {
return $var_name;
}
}
return false;
}
需要明确的是,在 PHP 中没有这样做的好方法,这可能是因为您不应该这样做.可能有更好的方法来做你想做的事情.
to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.
这篇关于如何在 PHP 中将变量名作为字符串获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PHP 中将变量名作为字符串获取?
基础教程推荐
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
