Home >Backend Development >PHP Tutorial >Variable name Bug analysis of a piece of code to obtain the variable name of a variable in PHP
Copy the code The code is as follows:
/**
* Get variable name
*
* @param $string
* @return $string
*
* $test = "helo";
* $test2 = "helo";
* getVarName($test2);
*/
function getVarName(&$src){
//Storage the current variable value
$save = $src;
//Storage all variables Value
$allvar = $GLOBALS;
//Do not traverse $GLOBALS directly in the function, stack problems will occur
foreach($allvar as $k=>$v){
//The variable values are the same, but they may not be the same Variable, because the values of multiple variables may be the same
if ($src == $v){
//Change the value of the current variable $src
$src = 'change';
//If $GLOBALS[$k] also As it changes, it's the same variable.
if ($src == $GLOBALS[$k]){
//echo "$$k name is $k
";
//Restore variable value
$src = $save;
return $k;
}
}
}
}
Copy the code The code is as follows:
$test2 = "hello";
$countNum=0;
echo getVarName($test2);
//Logically the output should be " test2", but the output is "countNum",
The above introduces the bug analysis of a piece of code for obtaining the variable name of a variable in PHP, including the variable name. I hope it will be helpful to friends who are interested in PHP tutorials.