Home >Backend Development >PHP Tutorial >Variable name Bug analysis of a piece of code to obtain the variable name of a variable in PHP

Variable name Bug analysis of a piece of code to obtain the variable name of a variable in PHP

WBOY
WBOYOriginal
2016-07-29 08:46:00927browse

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;
}
}
}
}


After copying it, I found that the test results are sometimes correct and sometimes wrong. After thinking about it for a long time, I finally figured it out. Although it is very simple, I still recorded it. I hope that students who encounter the same situation will pay attention. .
For example: Now I test

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",


because there is a problem with
if ($src == $v) in the function, such as $src="hello", there is a variable $countNUm=0 in $GLOBALS;
At this time, if ($src == $v) is judged during the loop, that is, "hello" == 0, the comparison result is true. During type conversion, "hello" is converted into an integer and is 0,
Then exit the loop , and got wrong results.
One solution is to change if ($src == $v) to if ($src===$v), which is identical.
If I understand it wrong, you are welcome to correct me and let us make progress together.

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn