bug analysis of a piece of code that gets the variable name of a variable in PHP

  • 2020-05-09 18:17:48
  • OfStack

 
/** 
*  Get the variable name  
* 
* @param $string 
* @return $string 
* 
* $test = "helo"; 
* $test2 = "helo"; 
* getVarName($test2); 
*/ 
function getVarName(&$src){ 
// Stores the value of the current variable  
$save = $src; 
// Stores all variable values  
$allvar = $GLOBALS; 
// Do not drag through functions $GLOBALS, There are stack issues  
foreach($allvar as $k=>$v){ 
// The variable has the same value, maybe not the same variable , Because multiple variables may have the same value  
if ($src == $v){ 
// Changing the current variable $src The value of the  
$src = 'change'; 
// if $GLOBALS[$k] And that is the same 1 A variable.  
if ($src == $GLOBALS[$k]){ 
//echo "\$$k name is $k 
"; 
// Restore variable value  
$src = $save; 
return $k; 
} 
} 
} 
} 

When copy came down, he found that the test results were sometimes right and sometimes wrong. After thinking for a long time, he finally figured it out. Although it was very simple, he still recorded it.
For example: now I test
 
$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's a problem here like $src="hello", $GLOBALS has a variable $countNUm=0;
At this time, if ($src == $v) is judged during the loop, that is, "hello"==0, and the comparison result is true. When the type is converted, "hello" is transformed to 0,
And then you get out of the loop, and you get the wrong result.
One solution is to replace if ($src ==$v) with if($src===$v), or identity.
If I understand wrong, you are welcome to correct, 1 progress.

Related articles: