Copy CodeThe code is as follows:
/**
* Get variable name
*
* @param $string
* @return $string
*
* $test = "Helo";
* $test 2 = "Helo";
* Getvarname ($test 2);
*/
Function Getvarname (& $SRC) {
Store current variable values
$save = $SRC;
Store all variable values
$allvar = $GLOBALS;
Do not traverse $globals directly in the function, there will be a stack problem
foreach ($allvar as $k = = $v) {
Variable values are the same, 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 changes, that is the same variable.
if ($src = = $GLOBALS [$k]) {
echo "\$ $k name is $k
";
Restore variable values
$SRC = $save;
return $k;
}
}
}
}
Copy down found this how test results sometimes wrong, think for a long time, finally understand, although very simple, but I still record, hope to meet the same situation of students attention.
For example: Now I'm testing
Copy the Code code as follows:
$test 2 = "Hello";
$countNum = 0;
Echo Getvarname ($test 2);
The reason should be output as "test2", but the output is "Countnum",
Because the functions in the
if ($src = = $v) There are problems such as $src= "Hello", $GLOBALS there is a variable $countnum=0;
At this time in the loop to determine if ($src = = $v), that is, "Hello" ==0, the result of the comparison is true, when the type conversion "Hello" to the shaping of 0,
It then exits the loop and gets the wrong result.
One solution is to change if ($src = = $v) to if ($src = = = $v), which is identity.
If I understand wrong, you are welcome to correct and improve together.
The above describes the variable name in PHP to get variable name of a section of code bug analysis, including the variable name of the content, I hope to be interested in PHP tutorial friends helpful.