假设我有这样的PHP代码:
$FooBar = "a string";
然后我需要一个这样的函数:
print_var_name($FooBar);
打印:
FooBar
有什么想法如何实现这一点?这在PHP中可能吗?
假设我有这样的PHP代码:
$FooBar = "a string";
然后我需要一个这样的函数:
print_var_name($FooBar);
打印:
FooBar
有什么想法如何实现这一点?这在PHP中可能吗?
我真的看不出用例……如果你将输入print_var_name($foobar)什么那么难(和不同)输入打印(“foobar”)代替?
因为即使你要在函数中使用这个,你也会得到变量的本地名称…
无论如何,这是反射手册,以防你需要什么。
您可以使用get_defined_vars()来查找与您试图查找的变量名称具有相同值的变量的名称。显然这并不总是有效,因为不同的变量通常有相同的值,但这是我能想到的唯一方法。
编辑:get_defined_vars()似乎没有正确工作,它返回'var',因为$var在函数本身中使用。$GLOBALS似乎可以,所以我把它改成了这个。
function print_var_name($var) {
foreach($GLOBALS as $var_name => $value) {
if ($value === $var) {
return $var_name;
}
}
return false;
}
编辑:需要明确的是,在PHP中没有好的方法来做到这一点,这可能是因为您不应该这样做。也许有更好的方法来做你想做的事情。
如果变量是可交换的,那么必须在某个地方有逻辑来决定使用哪个变量。你所需要做的就是在你做其他事情的时候,把变量名放在这个逻辑中的$variable中。
我想我们都很难理解你需要这个做什么。示例代码或对实际要做的事情的解释可能会有所帮助,但我怀疑您想得太多了。
您可能会考虑改变您的方法,并使用一个变量变量名?
$var_name = "FooBar";
$$var_name = "a string";
然后你就可以
print($var_name);
得到
FooBar
这里是PHP变量手册的链接
我也想不出有效的方法但我想到了这个。对于下面的有限用途,它是有效的。
耸耸肩
<?php
function varName( $v ) {
$trace = debug_backtrace();
$vLine = file( __FILE__ );
$fLine = $vLine[ $trace[0]['line'] - 1 ];
preg_match( "#\\$(\w+)#", $fLine, $match );
print_r( $match );
}
$foo = "knight";
$bar = array( 1, 2, 3 );
$baz = 12345;
varName( $foo );
varName( $bar );
varName( $baz );
?>
// Returns
Array
(
[0] => $foo
[1] => foo
)
Array
(
[0] => $bar
[1] => bar
)
Array
(
[0] => $baz
[1] => baz
)
它基于调用函数的行来工作,在那里它可以找到传入的参数。我认为它可以扩展到多个参数,但是,就像其他人说的,如果你能更好地解释情况,另一个解决方案可能会更好。
我实际上有一个有效的用例。
我有一个函数cacheVariable($var)(好吧,我有一个函数缓存($key, $value),但我想有一个函数如上所述)。
目的是:
$colour = 'blue';
cacheVariable($colour);
...
// another session
...
$myColour = getCachedVariable('colour');
我试过了
function cacheVariable($variable) {
$key = ${$variable}; // This doesn't help! It only gives 'variable'.
// do some caching using suitable backend such as apc, memcache or ramdisk
}
我也试过
function varName(&$var) {
$definedVariables = get_defined_vars();
$copyOfDefinedVariables = array();
foreach ($definedVariables as $variable=>$value) {
$copyOfDefinedVariables[$variable] = $value;
}
$oldVar = $var;
$var = !$var;
$difference = array_diff_assoc($definedVariables, $copyOfDefinedVariables);
$var = $oldVar;
return key(array_slice($difference, 0, 1, true));
}
但这也失败了……:(
当然,我可以继续做缓存(' color ', $ color),但我很懒,你知道…;)
所以,我想要的是一个函数,它得到一个变量的原始名称,因为它被传递给一个函数。在函数内部,我不可能知道这一点。在上面的第二个例子中,通过引用传递get_defined_vars()在一定程度上帮助了我(感谢Jean-Jacques Guegan的这个想法)。后一个函数开始工作,但它仍然只返回局部变量('variable',而不是' color ')。
我还没有尝试使用get_func_args()和get_func_arg(), ${}-构造和key()组合,但我认为它也会失败。
出于调试的原因,我做了一个检查函数。它就像print_r()的类固醇,很像Krumo,但对对象更有效一点。我想添加var名称检测,灵感来自于Nick Presta的帖子。它检测作为参数传递的任何表达式,而不仅仅是变量名。
这只是检测传递表达式的包装器函数。 大多数案子都没问题。 如果在同一行代码中多次调用该函数,则它将不起作用。
这很好: 死(检查($ this - > getUser()——> hasCredential(“删除”)));
Inspect()是检测传递表达式的函数。
我们得到:$this->getUser()->hasCredential("delete")
function inspect($label, $value = "__undefin_e_d__")
{
if($value == "__undefin_e_d__") {
/* The first argument is not the label but the
variable to inspect itself, so we need a label.
Let's try to find out it's name by peeking at
the source code.
*/
/* The reason for using an exotic string like
"__undefin_e_d__" instead of NULL here is that
inspected variables can also be NULL and I want
to inspect them anyway.
*/
$value = $label;
$bt = debug_backtrace();
$src = file($bt[0]["file"]);
$line = $src[ $bt[0]['line'] - 1 ];
// let's match the function call and the last closing bracket
preg_match( "#inspect\((.+)\)#", $line, $match );
/* let's count brackets to see how many of them actually belongs
to the var name
Eg: die(inspect($this->getUser()->hasCredential("delete")));
We want: $this->getUser()->hasCredential("delete")
*/
$max = strlen($match[1]);
$varname = "";
$c = 0;
for($i = 0; $i < $max; $i++){
if( $match[1]{$i} == "(" ) $c++;
elseif( $match[1]{$i} == ")" ) $c--;
if($c < 0) break;
$varname .= $match[1]{$i};
}
$label = $varname;
}
// $label now holds the name of the passed variable ($ included)
// Eg: inspect($hello)
// => $label = "$hello"
// or the whole expression evaluated
// Eg: inspect($this->getUser()->hasCredential("delete"))
// => $label = "$this->getUser()->hasCredential(\"delete\")"
// now the actual function call to the inspector method,
// passing the var name as the label:
// return dInspect::dump($label, $val);
// UPDATE: I commented this line because people got confused about
// the dInspect class, wich has nothing to do with the issue here.
echo("The label is: ".$label);
echo("The value is: ".$value);
}
下面是inspector函数(和我的dInspect类)的一个例子:
http://inspect.ip1.cc
该页面的文本是西班牙语,但代码简洁,非常容易理解。
我有这个:
debug_echo(array('$query'=>$query, '$nrUsers'=>$nrUsers, '$hdr'=>$hdr));
我更喜欢这样:
debug_echo($query, $nrUsers, $hdr);
现有函数显示一个带有红色轮廓的黄色框,并按名称和值显示每个变量。数组解决方案是可行的,但在需要时输入有点复杂。
这就是我的用例,是的,它确实与调试有关。我同意那些质疑其其他用途的人。
net上的Lucas提供了一种可靠的方法来检查变量是否存在。在他的示例中,他遍历变量的全局变量数组(或作用域数组)的副本,将值更改为随机生成的值,并在复制的数组中检查生成的值。
function variable_name( &$var, $scope=false, $prefix='UNIQUE', $suffix='VARIABLE' ){
if($scope) {
$vals = $scope;
} else {
$vals = $GLOBALS;
}
$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
然后尝试:
$a = 'asdf';
$b = 'asdf';
$c = FALSE;
$d = FALSE;
echo variable_name($a); // a
echo variable_name($b); // b
echo variable_name($c); // c
echo variable_name($d); // d
一定要查看他在PHP.net上的帖子:http://php.net/manual/en/language.variables.php
为什么不构建一个简单的函数,然后告诉它呢?
/**
* Prints out $obj for debug
*
* @param any_type $obj
* @param (string) $title
*/
function print_all( $obj, $title = false )
{
print "\n<div style=\"font-family:Arial;\">\n";
if( $title ) print "<div style=\"background-color:red; color:white; font-size:16px; font-weight:bold; margin:0; padding:10px; text-align:center;\">$title</div>\n";
print "<pre style=\"background-color:yellow; border:2px solid red; color:black; margin:0; padding:10px;\">\n\n";
var_export( $obj );
print "\n\n</pre>\n</div>\n";
}
print_all( $aUser, '$aUser' );
从php.net
@Alexandre -简短的解决方案
<?php
function vname(&$var, $scope=0)
{
$old = $var;
if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;
}
?>
@Lucas - usage
<?php
//1. Use of a variable contained in the global scope (default):
$my_global_variable = "My global string.";
echo vname($my_global_variable); // Outputs: my_global_variable
//2. Use of a local variable:
function my_local_func()
{
$my_local_variable = "My local string.";
return vname($my_local_variable, get_defined_vars());
}
echo my_local_func(); // Outputs: my_local_variable
//3. Use of an object property:
class myclass
{
public function __constructor()
{
$this->my_object_property = "My object property string.";
}
}
$obj = new myclass;
echo vname($obj->my_object_property, $obj); // Outputs: my_object_property
?>
这是我基于杰里米·鲁滕的解决方案
class DebugHelper {
function printVarNames($systemDefinedVars, $varNames) {
foreach ($systemDefinedVars as $var=>$value) {
if (in_array($var, $varNames )) {
var_dump($var);
var_dump($value);
}
}
}
}
使用它
DebugHelper::printVarNames(
$systemDefinedVars = get_defined_vars(),
$varNames=array('yourVar00', 'yourVar01')
);
许多回复质疑这样做的用处。然而,获取变量的引用是非常有用的。特别是在有对象和$this的情况下。我的解决方案适用于对象,以及属性定义的对象:
function getReference(&$var)
{
if(is_object($var))
$var->___uniqid = uniqid();
else
$var = serialize($var);
$name = getReference_traverse($var,$GLOBALS);
if(is_object($var))
unset($var->___uniqid);
else
$var = unserialize($var);
return "\${$name}";
}
function getReference_traverse(&$var,$arr)
{
if($name = array_search($var,$arr,true))
return "{$name}";
foreach($arr as $key=>$value)
if(is_object($value))
if($name = getReference_traverse($var,get_object_vars($value)))
return "{$key}->{$name}";
}
上面的例子:
class A
{
public function whatIs()
{
echo getReference($this);
}
}
$B = 12;
$C = 12;
$D = new A;
echo getReference($B)."<br/>"; //$B
echo getReference($C)."<br/>"; //$C
$D->whatIs(); //$D
为什么我们必须使用全局变量来获取变量名…我们可以像下面这样简单地使用。
$variableName = "ajaxmint";
echo getVarName('$variableName');
function getVarName($name) {
return str_replace('$','',$name);
}
使用此方法将用户变量从全局变量分离到当前的检查变量。
function get_user_var_defined ()
{
return array_slice($GLOBALS,8,count($GLOBALS)-8);
}
function get_var_name ($var)
{
$vuser = get_user_var_defined();
foreach($vuser as $key=>$value)
{
if($var===$value) return $key ;
}
}
我一直在找这个,但我决定把名字传进来,我通常把名字写在剪贴板上。
function VarTest($my_var,$my_var_name){
echo '$'.$my_var_name.': '.$my_var.'<br />';
}
$fruit='apple';
VarTest($fruit,'fruit');
从上面的答案改编为许多变量,具有良好的性能,只需一个$GLOBALS扫描许多
function compact_assoc(&$v1='__undefined__', &$v2='__undefined__',&$v3='__undefined__',&$v4='__undefined__',&$v5='__undefined__',&$v6='__undefined__',&$v7='__undefined__',&$v8='__undefined__',&$v9='__undefined__',&$v10='__undefined__',&$v11='__undefined__',&$v12='__undefined__',&$v13='__undefined__',&$v14='__undefined__',&$v15='__undefined__',&$v16='__undefined__',&$v17='__undefined__',&$v18='__undefined__',&$v19='__undefined__'
) {
$defined_vars=get_defined_vars();
$result=Array();
$reverse_key=Array();
$original_value=Array();
foreach( $defined_vars as $source_key => $source_value){
if($source_value==='__undefined__') break;
$original_value[$source_key]=$$source_key;
$new_test_value="PREFIX".rand()."SUFIX";
$reverse_key[$new_test_value]=$source_key;
$$source_key=$new_test_value;
}
foreach($GLOBALS as $key => &$value){
if( is_string($value) && isset($reverse_key[$value]) ) {
$result[$key]=&$value;
}
}
foreach( $original_value as $source_key => $original_value){
$$source_key=$original_value;
}
return $result;
}
$a = 'A';
$b = 'B';
$c = '999';
$myArray=Array ('id'=>'id123','name'=>'Foo');
print_r(compact_assoc($a,$b,$c,$myArray) );
//print
Array
(
[a] => A
[b] => B
[c] => 999
[myArray] => Array
(
[id] => id123
[name] => Foo
)
)
似乎没有人提到这是a)困难和b)不明智的根本原因:
A "variable" is just a symbol pointing at something else. In PHP, it internally points to something called a "zval", which can actually be used for multiple variables simultaneously, either because they have the same value (PHP implements something called "copy-on-write" so that $foo = $bar doesn't need to allocate extra memory straight away) or because they have been assigned (or passed to a function) by reference (e.g. $foo =& $bar). So a zval has no name. When you pass a parameter to a function you are creating a new variable (even if it's a reference). You could pass something anonymous, like "hello", but once inside your function, it's whatever variable you name it as. This is fairly fundamental to code separation: if a function relied on what a variable used to be called, it would be more like a goto than a properly separate function. Global variables are generally considered a bad idea. A lot of the examples here assume that the variable you want to "reflect" can be found in $GLOBALS, but this will only be true if you've structured your code badly and variables aren't scoped to some function or object. Variable names are there to help programmers read their code. Renaming variables to better suit their purpose is a very common refactoring practice, and the whole point is that it doesn't make any difference.
现在,我理解这种调试的愿望(尽管一些建议的用法远远超出了这一点),但作为一种通用的解决方案,它实际上并没有你想象的那么有用:如果你的调试函数说你的变量是“$file”,那仍然可能是你代码中数十个“$file”变量中的任何一个,或者一个你称为“$filename”的变量,但传递给一个参数为“$file”的函数。
更有用的信息是在代码中调用调试函数的位置。因为你可以在你的编辑器中快速找到它,你可以看到你为自己输出的变量,甚至可以一次性将整个表达式传递给它(例如debug('$foo + $bar = ')。($foo + $bar))。
为此,你可以在调试函数的顶部使用这段代码:
$backtrace = debug_backtrace();
echo '# Debug function called from ' . $backtrace[0]['file'] . ' at line ' . $backtrace[0]['line'];
它可能被认为是快速和肮脏的,但我个人倾向于使用这样的函数/方法:
public function getVarName($var) {
$tmp = array($var => '');
$keys = array_keys($tmp);
return trim($keys[0]);
}
基本上,它只是创建一个包含一个空/空元素的关联数组,使用需要名称的变量作为键。
然后使用array_keys获取该键的值并返回。
显然,这很快就会变得混乱,在生产环境中不可取,但它可以解决所提出的问题。
您可以使用compact()来实现这一点。
$FooBar = "a string";
$newArray = compact('FooBar');
这将创建一个以变量名为键的关联数组。然后可以在需要的地方使用键名循环遍历数组。
foreach($newarray as $key => $value) {
echo $key;
}
我认为你想知道变量名和它的值。您可以使用关联数组来实现这一点。
为数组键使用变量名:
$vars = array('FooBar' => 'a string');
当你想获取变量名时,使用array_keys($vars),它将返回一个数组,这些变量名是你的$vars数组中使用的键。
这正是你想要的-这是一个随时可以使用的“复制并导入”函数,它会回显给定变量的名称:
function print_var_name(){
// read backtrace
$bt = debug_backtrace();
// read file
$file = file($bt[0]['file']);
// select exact print_var_name($varname) line
$src = $file[$bt[0]['line']-1];
// search pattern
$pat = '#(.*)'.__FUNCTION__.' *?\( *?(.*) *?\)(.*)#i';
// extract $varname from match no 2
$var = preg_replace($pat, '$2', $src);
// print to browser
echo '<pre>' . trim($var) . ' = ' . print_r(current(func_get_args()), true) . '</pre>';
}
用法:print_var_name ($ FooBar)
打印:FooBar
提示 现在你可以重命名函数,它仍然可以工作,也可以在一行中多次使用该函数!感谢@Cliffordlife 我添加了一个更好的输出!多亏了@Blue-Water
我知道这个问题很老了,而且已经有人回答了,但我其实是在找这个。我把这个答案贴出来是为了给大家节省一点时间来完善一些答案。
选项1:
$data = array('$FooBar');
$vars = [];
$vars = preg_replace('/^\\$/', '', $data);
$varname = key(compact($vars));
echo $varname;
打印:
FooBar
不管出于什么原因,你会发现自己处于这样的情况下,它确实有效。
. 选项2:
$FooBar = "a string";
$varname = trim(array_search($FooBar, $GLOBALS), " \t.");
echo $varname;
如果$FooBar拥有一个唯一的值,它将打印'FooBar'。如果$FooBar为空或空,它将打印找到的第一个空字符串或空字符串的名称。
它可以这样使用:
if (isset($FooBar) && !is_null($FooBar) && !empty($FooBar)) {
$FooBar = "a string";
$varname = trim(array_search($FooBar, $GLOBALS), " \t.");
}
我就是这么做的
function getVar(&$var) {
$tmp = $var; // store the variable value
$var = '_$_%&33xc$%^*7_r4'; // give the variable a new unique value
$name = array_search($var, $GLOBALS); // search $GLOBALS for that unique value and return the key(variable)
$var = $tmp; // restore the variable old value
return $name;
}
使用
$city = "San Francisco";
echo getVar($city); // city
注意:一些PHP 7版本将不能正常工作,因为array_search与$GLOBALS的错误,但所有其他版本都可以正常工作。
请看这个https://3v4l.org/UMW7V
PHP中没有可以输出变量名的预定义函数。但是,您可以使用get_defined_vars()的结果,该结果返回范围内定义的所有变量,包括名称和值。这里有一个例子:
<?php
// Function for determining the name of a variable
function getVarName(&$var, $definedVars=null) {
$definedVars = (!is_array($definedVars) ? $GLOBALS : $definedVars);
$val = $var;
$rand = 1;
while (in_array($rand, $definedVars, true)) {
$rand = md5(mt_rand(10000, 1000000));
}
$var = $rand;
foreach ($definedVars as $dvName=>$dvVal) {
if ($dvVal === $rand) {
$var = $val;
return $dvName;
}
}
return null;
}
// the name of $a is to be determined.
$a = 1;
// Determine the name of $a
echo getVarName($a);
?>
阅读更多在如何获得一个变量名作为一个字符串在PHP?
其他用途:
耸耸肩
function varsToArrayAssoc(...$arguments){
$bt = debug_backtrace();
$file = file($bt[0]['file']);
$src = $file[$bt[0]['line']-1];
$pat = '#(.*)'.__FUNCTION__.' *?\( *?(.*) *?\)(.*)#i';
$vars =explode(',',substr_replace(trim(preg_replace($pat, '$2', $src)) ,"", -1));
$result=[];
foreach(func_get_args() as $key=>$v){
$index=trim(explode('$',$vars[$key])[1]);
$result[$index]=$v;
}
return $result;
}
$a=12;
$b=13;
$c=123;
$d='aa';
var_dump(varsToArrayAssoc($a,$b,$c,$d));