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

Bug analysis of a piece of code to obtain the variable name of a variable in PHP_PHP Tutorial

WBOY
Release: 2016-07-21 15:26:55
Original
914 people have browsed it

Copy 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 variable values
$allvar = $GLOBALS;
//Don’t traverse $GLOBALS in the function, it will A stack problem occurs
foreach($allvar as $k=>$v){
//The variable values ​​are the same, they may not be the same variables, 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 changes, it is the same variable.
if ($src == $GLOBALS[$k]){
//echo "$$k name is $k
";
//Restore variable value
$src = $save;
return $k;
}
}
}
}

After copying it, I found out that the test results are sometimes correct and sometimes incorrect. After thinking about it for a long time, I finally figured it out. Although it is very simple, I still recorded it in the hope that students who encounter the same situation will pay attention.
For example: Now I test
Copy 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 in the function
if ($src == $v) There are problems here, such as $src="hello", there is a variable $countNUm=0 in $GLOBALS;
At this time, if ($src == $v), that is, "hello"==0, the comparison result is true. During type conversion, "hello" is converted into an integer and is 0.
Then the loop exits and the wrong result is obtained.
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 we will make progress together.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323861.htmlTechArticleCopy the code as follows: /*** Get the variable name * * @param $string * @return $string * * $test = "helo"; * $test2 = "helo"; * getVarName($test2);*/ function getVarName( //Storage...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template